text
stringlengths 54
60.6k
|
|---|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <hintids.hxx>
#include <com/sun/star/i18n/ScriptType.hpp>
#include <fmtcntnt.hxx>
#include <txatbase.hxx>
#include <frmatr.hxx>
#include <viscrs.hxx>
#include <callnk.hxx>
#include <crsrsh.hxx>
#include <doc.hxx>
#include <frmfmt.hxx>
#include <txtfrm.hxx>
#include <tabfrm.hxx>
#include <rowfrm.hxx>
#include <fmtfsize.hxx>
#include <ndtxt.hxx>
#include <flyfrm.hxx>
#include <breakit.hxx>
#include<vcl/window.hxx>
SwCallLink::SwCallLink( SwCrsrShell & rSh, sal_uLong nAktNode, xub_StrLen nAktCntnt,
sal_uInt8 nAktNdTyp, long nLRPos, bool bAktSelection )
: rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ),
nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos ),
bHasSelection( bAktSelection )
{
}
SwCallLink::SwCallLink( SwCrsrShell & rSh )
: rShell( rSh )
{
// remember SPoint-values of current cursor
SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode();
nNode = rNd.GetIndex();
nCntnt = pCrsr->GetPoint()->nContent.GetIndex();
nNdTyp = rNd.GetNodeType();
bHasSelection = ( *pCrsr->GetPoint() != *pCrsr->GetMark() );
if( rNd.IsTxtNode() )
nLeftFrmPos = SwCallLink::getLayoutFrm( rShell.GetLayout(), (SwTxtNode&)rNd, nCntnt,
!rShell.ActionPend() );
else
{
nLeftFrmPos = 0;
// A special treatment for SwFeShell:
// When deleting the header/footer, footnotes SwFeShell sets the
// Cursor to NULL (Node + Content).
// If the Cursor is not on a CntntNode (ContentNode) this fact gets
// saved in NdType.
if( ND_CONTENTNODE & nNdTyp )
nNdTyp = 0;
}
}
static void lcl_notifyRow(const SwCntntNode* pNode, SwCrsrShell& rShell)
{
if ( pNode != NULL )
{
SwFrm *myFrm = pNode->getLayoutFrm( rShell.GetLayout() );
if (myFrm!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm->FindRowFrm();
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
// Avoid redrawing the complete row if there are no nested tables
bool bHasTable = false;
SwFrm *pCell = pRow->GetLower();
for (; pCell && !bHasTable; pCell = pCell->GetNext())
{
SwFrm *pContent = pCell->GetLower();
for (; pContent && !bHasTable; pContent = pContent->GetNext())
if (pContent->GetType() == FRM_TAB)
bHasTable = true;
}
if (bHasTable)
{
SwFmtFrmSize pSize = pLine->GetFrmFmt()->GetFrmSize();
pRow->ModifyNotification(NULL, &pSize);
}
}
}
}
}
SwCallLink::~SwCallLink()
{
if( !nNdTyp || !rShell.m_bCallChgLnk ) // see ctor
return ;
// If travelling over Nodes check formats and register them anew at the
// new Node.
SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwCntntNode * pCNd = pCurCrsr->GetCntntNode();
if( !pCNd )
return;
lcl_notifyRow(pCNd, rShell);
const SwDoc *pDoc=rShell.GetDoc();
const SwCntntNode *pNode = NULL;
if ( ( pDoc != NULL && nNode < pDoc->GetNodes( ).Count( ) ) )
{
pNode = pDoc->GetNodes()[nNode]->GetCntntNode();
}
lcl_notifyRow(pNode, rShell);
xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex();
sal_uInt16 nNdWhich = pCNd->GetNodeType();
sal_uLong nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex();
// Register the Shell as dependent at the current Node. By doing this all
// attribute changes can be signaled over the link.
pCNd->Add( &rShell );
if( nNdTyp != nNdWhich || nNode != nAktNode )
{
// Every time a switch between nodes occurs, there is a chance that
// new attributes do apply - meaning text-attributes.
// So the currently applying attributes would have to be determined.
// That can be done in one go by the handler.
rShell.CallChgLnk();
}
else if( !bHasSelection != !(*pCurCrsr->GetPoint() != *pCurCrsr->GetMark()) )
{
// always call change link when selection changes
rShell.CallChgLnk();
}
else if( rShell.m_aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich &&
nCntnt != nAktCntnt )
{
// If travelling with left/right only and the frame is
// unchanged (columns!) then check text hints.
if( nLeftFrmPos == SwCallLink::getLayoutFrm( rShell.GetLayout(), (SwTxtNode&)*pCNd, nAktCntnt,
!rShell.ActionPend() ) &&
(( nCmp = nCntnt ) + 1 == nAktCntnt || // Right
nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left
{
if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & select
++nCmp;
if ( ((SwTxtNode*)pCNd)->HasHints() )
{
const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints();
sal_uInt16 n;
xub_StrLen nStart;
const xub_StrLen *pEnd;
for( n = 0; n < rHts.Count(); n++ )
{
const SwTxtAttr* pHt = rHts[ n ];
pEnd = pHt->GetEnd();
nStart = *pHt->GetStart();
// If "only start" or "start and end equal" then call on
// every overflow of start.
if( ( !pEnd || ( nStart == *pEnd ) ) &&
( nStart == nCntnt || nStart == nAktCntnt) )
{
rShell.CallChgLnk();
return;
}
// If the attribute has an area and that area is not empty ...
else if( pEnd && nStart < *pEnd &&
// ... then test if travelling occurred via start/end.
( nStart == nCmp ||
( pHt->DontExpand() ? nCmp == *pEnd-1
: nCmp == *pEnd ) ))
{
rShell.CallChgLnk();
return;
}
nStart = 0;
}
}
if( g_pBreakIt->GetBreakIter().is() )
{
const String& rTxt = ((SwTxtNode*)pCNd)->GetTxt();
if( !nCmp ||
g_pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp )
!= g_pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp - 1 ))
{
rShell.CallChgLnk();
return;
}
}
}
else
// If travelling more than one character with home/end/.. then
// always call ChgLnk, because it can not be determined here what
// has changed. Something may have changed.
rShell.CallChgLnk();
}
const SwFrm* pFrm;
const SwFlyFrm *pFlyFrm;
if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->getLayoutFrm(rShell.GetLayout(),0,0,sal_False) ) &&
0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() )
{
const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx();
OSL_ENSURE( pIndex, "Fly without Cntnt" );
if (!pIndex)
return;
const SwNode& rStNd = pIndex->GetNode();
if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode ||
nNode > rStNd.EndOfSectionIndex() )
rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() );
}
}
long SwCallLink::getLayoutFrm( const SwRootFrm* pRoot, SwTxtNode& rNd, xub_StrLen nCntPos, sal_Bool bCalcFrm )
{
SwTxtFrm* pFrm = (SwTxtFrm*)rNd.getLayoutFrm(pRoot,0,0,bCalcFrm), *pNext = pFrm;
if ( pFrm && !pFrm->IsHiddenNow() )
{
if( pFrm->HasFollow() )
while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) &&
nCntPos >= pNext->GetOfst() )
pFrm = pNext;
return pFrm->Frm().Left();
}
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>String to OUString<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include <hintids.hxx>
#include <com/sun/star/i18n/ScriptType.hpp>
#include <fmtcntnt.hxx>
#include <txatbase.hxx>
#include <frmatr.hxx>
#include <viscrs.hxx>
#include <callnk.hxx>
#include <crsrsh.hxx>
#include <doc.hxx>
#include <frmfmt.hxx>
#include <txtfrm.hxx>
#include <tabfrm.hxx>
#include <rowfrm.hxx>
#include <fmtfsize.hxx>
#include <ndtxt.hxx>
#include <flyfrm.hxx>
#include <breakit.hxx>
#include<vcl/window.hxx>
SwCallLink::SwCallLink( SwCrsrShell & rSh, sal_uLong nAktNode, xub_StrLen nAktCntnt,
sal_uInt8 nAktNdTyp, long nLRPos, bool bAktSelection )
: rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ),
nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos ),
bHasSelection( bAktSelection )
{
}
SwCallLink::SwCallLink( SwCrsrShell & rSh )
: rShell( rSh )
{
// remember SPoint-values of current cursor
SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode();
nNode = rNd.GetIndex();
nCntnt = pCrsr->GetPoint()->nContent.GetIndex();
nNdTyp = rNd.GetNodeType();
bHasSelection = ( *pCrsr->GetPoint() != *pCrsr->GetMark() );
if( rNd.IsTxtNode() )
nLeftFrmPos = SwCallLink::getLayoutFrm( rShell.GetLayout(), (SwTxtNode&)rNd, nCntnt,
!rShell.ActionPend() );
else
{
nLeftFrmPos = 0;
// A special treatment for SwFeShell:
// When deleting the header/footer, footnotes SwFeShell sets the
// Cursor to NULL (Node + Content).
// If the Cursor is not on a CntntNode (ContentNode) this fact gets
// saved in NdType.
if( ND_CONTENTNODE & nNdTyp )
nNdTyp = 0;
}
}
static void lcl_notifyRow(const SwCntntNode* pNode, SwCrsrShell& rShell)
{
if ( pNode != NULL )
{
SwFrm *myFrm = pNode->getLayoutFrm( rShell.GetLayout() );
if (myFrm!=NULL)
{
// We need to emulated a change of the row height in order
// to have the complete row redrawn
SwRowFrm* pRow = myFrm->FindRowFrm();
if ( pRow )
{
const SwTableLine* pLine = pRow->GetTabLine( );
// Avoid redrawing the complete row if there are no nested tables
bool bHasTable = false;
SwFrm *pCell = pRow->GetLower();
for (; pCell && !bHasTable; pCell = pCell->GetNext())
{
SwFrm *pContent = pCell->GetLower();
for (; pContent && !bHasTable; pContent = pContent->GetNext())
if (pContent->GetType() == FRM_TAB)
bHasTable = true;
}
if (bHasTable)
{
SwFmtFrmSize pSize = pLine->GetFrmFmt()->GetFrmSize();
pRow->ModifyNotification(NULL, &pSize);
}
}
}
}
}
SwCallLink::~SwCallLink()
{
if( !nNdTyp || !rShell.m_bCallChgLnk ) // see ctor
return ;
// If travelling over Nodes check formats and register them anew at the
// new Node.
SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwCntntNode * pCNd = pCurCrsr->GetCntntNode();
if( !pCNd )
return;
lcl_notifyRow(pCNd, rShell);
const SwDoc *pDoc=rShell.GetDoc();
const SwCntntNode *pNode = NULL;
if ( ( pDoc != NULL && nNode < pDoc->GetNodes( ).Count( ) ) )
{
pNode = pDoc->GetNodes()[nNode]->GetCntntNode();
}
lcl_notifyRow(pNode, rShell);
xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex();
sal_uInt16 nNdWhich = pCNd->GetNodeType();
sal_uLong nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex();
// Register the Shell as dependent at the current Node. By doing this all
// attribute changes can be signaled over the link.
pCNd->Add( &rShell );
if( nNdTyp != nNdWhich || nNode != nAktNode )
{
// Every time a switch between nodes occurs, there is a chance that
// new attributes do apply - meaning text-attributes.
// So the currently applying attributes would have to be determined.
// That can be done in one go by the handler.
rShell.CallChgLnk();
}
else if( !bHasSelection != !(*pCurCrsr->GetPoint() != *pCurCrsr->GetMark()) )
{
// always call change link when selection changes
rShell.CallChgLnk();
}
else if( rShell.m_aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich &&
nCntnt != nAktCntnt )
{
// If travelling with left/right only and the frame is
// unchanged (columns!) then check text hints.
if( nLeftFrmPos == SwCallLink::getLayoutFrm( rShell.GetLayout(), (SwTxtNode&)*pCNd, nAktCntnt,
!rShell.ActionPend() ) &&
(( nCmp = nCntnt ) + 1 == nAktCntnt || // Right
nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left
{
if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & select
++nCmp;
if ( ((SwTxtNode*)pCNd)->HasHints() )
{
const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints();
sal_uInt16 n;
xub_StrLen nStart;
const xub_StrLen *pEnd;
for( n = 0; n < rHts.Count(); n++ )
{
const SwTxtAttr* pHt = rHts[ n ];
pEnd = pHt->GetEnd();
nStart = *pHt->GetStart();
// If "only start" or "start and end equal" then call on
// every overflow of start.
if( ( !pEnd || ( nStart == *pEnd ) ) &&
( nStart == nCntnt || nStart == nAktCntnt) )
{
rShell.CallChgLnk();
return;
}
// If the attribute has an area and that area is not empty ...
else if( pEnd && nStart < *pEnd &&
// ... then test if travelling occurred via start/end.
( nStart == nCmp ||
( pHt->DontExpand() ? nCmp == *pEnd-1
: nCmp == *pEnd ) ))
{
rShell.CallChgLnk();
return;
}
nStart = 0;
}
}
if( g_pBreakIt->GetBreakIter().is() )
{
const OUString rTxt = ((SwTxtNode*)pCNd)->GetTxt();
if( !nCmp ||
g_pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp )
!= g_pBreakIt->GetBreakIter()->getScriptType( rTxt, nCmp - 1 ))
{
rShell.CallChgLnk();
return;
}
}
}
else
// If travelling more than one character with home/end/.. then
// always call ChgLnk, because it can not be determined here what
// has changed. Something may have changed.
rShell.CallChgLnk();
}
const SwFrm* pFrm;
const SwFlyFrm *pFlyFrm;
if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->getLayoutFrm(rShell.GetLayout(),0,0,sal_False) ) &&
0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() )
{
const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx();
OSL_ENSURE( pIndex, "Fly without Cntnt" );
if (!pIndex)
return;
const SwNode& rStNd = pIndex->GetNode();
if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode ||
nNode > rStNd.EndOfSectionIndex() )
rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() );
}
}
long SwCallLink::getLayoutFrm( const SwRootFrm* pRoot, SwTxtNode& rNd, xub_StrLen nCntPos, sal_Bool bCalcFrm )
{
SwTxtFrm* pFrm = (SwTxtFrm*)rNd.getLayoutFrm(pRoot,0,0,bCalcFrm), *pNext = pFrm;
if ( pFrm && !pFrm->IsHiddenNow() )
{
if( pFrm->HasFollow() )
while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) &&
nCntPos >= pNext->GetOfst() )
pFrm = pNext;
return pFrm->Frm().Left();
}
return 0;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactoftableobj.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SDR_CONTACT_VIEWCONTACTOFTABLEOBJ_HXX
#define _SDR_CONTACT_VIEWCONTACTOFTABLEOBJ_HXX
#include <svx/sdr/contact/viewcontactofsdrobj.hxx>
//////////////////////////////////////////////////////////////////////////////
// predeclarations
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace table
{
class SdrTableObj;
}
namespace contact
{
class ViewContactOfTableObj : public ViewContactOfSdrObj
{
protected:
// internal access to SdrTextObj
::sdr::table::SdrTableObj& GetTextObj() const
{
return (::sdr::table::SdrTableObj&)GetSdrObject();
}
public:
// basic constructor, used from SdrObject.
ViewContactOfTableObj(::sdr::table::SdrTableObj& rTextObj);
// The destructor. When PrepareDelete() was not called before (see there)
// warnings will be generated in debug version if there are still contacts
// existing.
virtual ~ViewContactOfTableObj();
};
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif
// eof
<commit_msg>INTEGRATION: CWS aw033 (1.2.4); FILE MERGED 2008/07/10 13:00:59 aw 1.2.4.3: #i39532# XOutputDevice removed, PrepareDelete removed 2008/05/14 14:01:46 aw 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008/03/31 05:53:01 aw 1.2.4.1: in-between ersion of the primitive transition<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewcontactoftableobj.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SDR_CONTACT_VIEWCONTACTOFTABLEOBJ_HXX
#define _SDR_CONTACT_VIEWCONTACTOFTABLEOBJ_HXX
#include <svx/sdr/contact/viewcontactofsdrobj.hxx>
//////////////////////////////////////////////////////////////////////////////
// predeclarations
//////////////////////////////////////////////////////////////////////////////
namespace sdr
{
namespace table
{
class SdrTableObj;
}
namespace contact
{
class ViewContactOfTableObj : public ViewContactOfSdrObj
{
protected:
// internal access to SdrTextObj
::sdr::table::SdrTableObj& GetTableObj() const
{
return (::sdr::table::SdrTableObj&)GetSdrObject();
}
// This method is responsible for creating the graphical visualisation data derived ONLY from
// the model data
virtual drawinglayer::primitive2d::Primitive2DSequence createViewIndependentPrimitive2DSequence() const;
public:
// basic constructor, used from SdrObject.
ViewContactOfTableObj(::sdr::table::SdrTableObj& rTextObj);
virtual ~ViewContactOfTableObj();
};
} // end of namespace contact
} // end of namespace sdr
//////////////////////////////////////////////////////////////////////////////
#endif
// eof
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: callnk.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-19 00:08:17 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CALLNK_HXX
#define _CALLNK_HXX
#include <tools/solar.h>
class SwCrsrShell;
class SwTxtNode;
class SwCallLink
{
public:
SwCrsrShell & rShell;
ULONG nNode;
xub_StrLen nCntnt;
BYTE nNdTyp;
long nLeftFrmPos;
SwCallLink( SwCrsrShell & rSh );
SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt,
BYTE nAktNdTyp, long nLRPos );
~SwCallLink();
static long GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm );
};
#endif // _CALLNK_HXX
<commit_msg>INTEGRATION: CWS sw011 (1.1.1.1.190); FILE MERGED 2003/04/11 10:03:50 dvo 1.1.1.1.190.1: #108801# always update toolbar (etc.) when whether we have a text selection changes<commit_after>/*************************************************************************
*
* $RCSfile: callnk.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2003-04-17 16:03:53 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CALLNK_HXX
#define _CALLNK_HXX
#include <tools/solar.h>
class SwCrsrShell;
class SwTxtNode;
class SwCallLink
{
public:
SwCrsrShell & rShell;
ULONG nNode;
xub_StrLen nCntnt;
BYTE nNdTyp;
long nLeftFrmPos;
bool bHasSelection;
SwCallLink( SwCrsrShell & rSh );
SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt,
BYTE nAktNdTyp, long nLRPos,
bool bAktSelection );
~SwCallLink();
static long GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm );
};
#endif // _CALLNK_HXX
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////////
//
// BSD 3-Clause License
//
// Copyright (c) 2019, University of California, San Diego.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 "AntennaRepair.h"
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "Net.h"
#include "Pin.h"
#include "grt/GlobalRouter.h"
#include "utl/Logger.h"
namespace grt {
using utl::GRT;
AntennaRepair::AntennaRepair(GlobalRouter* grouter,
ant::AntennaChecker* arc,
dpl::Opendp* opendp,
odb::dbDatabase* db,
utl::Logger* logger)
: _grouter(grouter), _arc(arc), _opendp(opendp), _db(db), _logger(logger)
{
_block = _db->getChip()->getBlock();
}
int AntennaRepair::checkAntennaViolations(NetRouteMap& routing,
int maxRoutingLayer,
odb::dbMTerm* diodeMTerm)
{
odb::dbTech* tech = _db->getTech();
_arc->load_antenna_rules();
std::map<int, odb::dbTechVia*> defaultVias
= _grouter->getDefaultVias(maxRoutingLayer);
for (auto net_route : routing) {
odb::dbNet* db_net = net_route.first;
GRoute& route = net_route.second;
odb::dbWire* wire = odb::dbWire::create(db_net);
if (wire != nullptr) {
odb::dbWireEncoder wireEncoder;
wireEncoder.begin(wire);
odb::dbWireType wireType = odb::dbWireType::ROUTED;
for (GSegment& seg : route) {
if (std::abs(seg.initLayer - seg.finalLayer) > 1) {
_logger->error(GRT, 68, "Global route segment not valid.");
}
int x1 = seg.initX;
int y1 = seg.initY;
int x2 = seg.finalX;
int y2 = seg.finalY;
int l1 = seg.initLayer;
int l2 = seg.finalLayer;
odb::dbTechLayer* currLayer = tech->findRoutingLayer(l1);
if (l1 == l2) { // Add wire
if (x1 == x2 && y1 == y2)
continue;
wireEncoder.newPath(currLayer, wireType);
wireEncoder.addPoint(x1, y1);
wireEncoder.addPoint(x2, y2);
} else { // Add via
int bottomLayer = (l1 < l2) ? l1 : l2;
wireEncoder.newPath(currLayer, wireType);
wireEncoder.addPoint(x1, y1);
wireEncoder.addTechVia(defaultVias[bottomLayer]);
}
}
wireEncoder.end();
odb::orderWires(db_net, false, false);
std::vector<ant::VINFO> netViol = _arc->get_net_antenna_violations(
db_net,
diodeMTerm->getMaster()->getConstName(),
diodeMTerm->getConstName());
if (!netViol.empty()) {
_antennaViolations[db_net] = netViol;
_grouter->addDirtyNet(db_net);
}
odb::dbWire::destroy(wire);
} else {
_logger->error(GRT, 221, "Cannot create wire for net {}.", db_net->getConstName());
}
}
_logger->info(GRT, 12, "Antenna violations: {}", _antennaViolations.size());
return _antennaViolations.size();
}
void AntennaRepair::fixAntennas(odb::dbMTerm* diodeMTerm)
{
int siteWidth = -1;
int cnt = 0;
r_tree fixedInsts;
auto rows = _block->getRows();
for (odb::dbRow* db_row : rows) {
odb::dbSite* site = db_row->getSite();
int site_width = site->getWidth();
if (siteWidth == -1) {
siteWidth = site_width;
}
if (siteWidth != site_width) {
_logger->warn(GRT, 27, "Design has rows with different site widths.");
}
}
deleteFillerCells();
setInstsPlacementStatus(odb::dbPlacementStatus::FIRM);
getFixedInstances(fixedInsts);
for (auto const& violation : _antennaViolations) {
odb::dbNet* net = violation.first;
for (int i = 0; i < violation.second.size(); i++) {
for (odb::dbITerm* sinkITerm : violation.second[i].iterms) {
odb::dbInst* sinkInst = sinkITerm->getInst();
for (int j = 0; j < violation.second[i].antenna_cell_nums; j++) {
std::string antennaInstName = "ANTENNA_" + std::to_string(cnt);
insertDiode(net,
diodeMTerm,
sinkInst,
sinkITerm,
antennaInstName,
siteWidth,
fixedInsts);
cnt++;
}
}
}
}
}
void AntennaRepair::legalizePlacedCells()
{
AntennaCbk* cbk = new AntennaCbk(_grouter);
cbk->addOwner(_block);
_opendp->detailedPlacement(0);
_opendp->checkPlacement(false);
cbk->removeOwner();
// After legalize placement, diodes and violated insts don't need to be FIRM
setInstsPlacementStatus(odb::dbPlacementStatus::PLACED);
}
void AntennaRepair::deleteFillerCells()
{
int fillerCnt = 0;
for (odb::dbInst* inst : _block->getInsts()) {
if (inst->getMaster()->getType() == odb::dbMasterType::CORE_SPACER) {
fillerCnt++;
odb::dbInst::destroy(inst);
}
}
if (fillerCnt > 0) {
_logger->info(GRT, 11, "Deleted {} filler cells.", fillerCnt);
}
}
void AntennaRepair::insertDiode(odb::dbNet* net,
odb::dbMTerm* diodeMTerm,
odb::dbInst* sinkInst,
odb::dbITerm* sinkITerm,
std::string antennaInstName,
int siteWidth,
r_tree& fixedInsts)
{
bool legallyPlaced = false;
bool placeAtLeft = true;
int leftOffset = 0;
int rightOffset = 0;
int offset;
std::string netName = net->getConstName();
odb::dbMaster* antennaMaster = diodeMTerm->getMaster();
int instLocX, instLocY, instWidth;
odb::dbBox* sinkBBox = sinkInst->getBBox();
instLocX = sinkBBox->xMin();
instLocY = sinkBBox->yMin();
instWidth = sinkBBox->xMax() - sinkBBox->xMin();
odb::dbOrientType instOrient = sinkInst->getOrient();
odb::dbInst* antennaInst
= odb::dbInst::create(_block, antennaMaster, antennaInstName.c_str());
odb::dbITerm* antennaITerm
= antennaInst->findITerm(diodeMTerm->getConstName());
odb::dbBox* antennaBBox = antennaInst->getBBox();
int antennaWidth = antennaBBox->xMax() - antennaBBox->xMin();
// Use R-tree to check if diode will not overlap or cause 1-site spacing with
// other cells
int leftPad = _opendp->padGlobalLeft();
int rightPad = _opendp->padGlobalRight();
std::vector<value> overlapInsts;
while (!legallyPlaced) {
if (placeAtLeft) {
offset = -(antennaWidth + leftOffset * siteWidth);
leftOffset++;
placeAtLeft = false;
} else {
offset = instWidth + rightOffset * siteWidth;
rightOffset++;
placeAtLeft = true;
}
antennaInst->setOrient(instOrient);
antennaInst->setLocation(instLocX + offset, instLocY);
odb::dbBox* instBox = antennaInst->getBBox();
box box(point(instBox->xMin() - ((leftPad + rightPad) * siteWidth) + 1,
instBox->yMin() + 1),
point(instBox->xMax() + ((leftPad + rightPad) * siteWidth) - 1,
instBox->yMax() - 1));
fixedInsts.query(bgi::intersects(box), std::back_inserter(overlapInsts));
odb::Rect coreArea;
_block->getCoreArea(coreArea);
if (overlapInsts.empty() && instBox->xMin() >= coreArea.xMin()
&& instBox->xMax() <= coreArea.xMax()) {
legallyPlaced = true;
}
overlapInsts.clear();
}
antennaInst->setPlacementStatus(odb::dbPlacementStatus::FIRM);
odb::dbITerm::connect(antennaITerm, net);
_diodeInsts.push_back(antennaInst);
// Add diode to the R-tree of fixed instances
int fixedInstId = fixedInsts.size();
odb::dbBox* instBox = antennaInst->getBBox();
box b(point(instBox->xMin(), instBox->yMin()),
point(instBox->xMax(), instBox->yMax()));
value v(b, fixedInstId);
fixedInsts.insert(v);
fixedInstId++;
}
void AntennaRepair::getFixedInstances(r_tree& fixedInsts)
{
int fixedInstId = 0;
for (odb::dbInst* inst : _block->getInsts()) {
if (inst->getPlacementStatus() == odb::dbPlacementStatus::FIRM) {
odb::dbBox* instBox = inst->getBBox();
box b(point(instBox->xMin(), instBox->yMin()),
point(instBox->xMax(), instBox->yMax()));
value v(b, fixedInstId);
fixedInsts.insert(v);
fixedInstId++;
}
}
}
void AntennaRepair::setInstsPlacementStatus(
odb::dbPlacementStatus placementStatus)
{
for (auto const& violation : _antennaViolations) {
for (int i = 0; i < violation.second.size(); i++) {
for (odb::dbITerm* sinkITerm : violation.second[i].iterms) {
sinkITerm->getInst()->setPlacementStatus(placementStatus);
}
}
}
for (odb::dbInst* diodeInst : _diodeInsts) {
diodeInst->setPlacementStatus(placementStatus);
}
}
AntennaCbk::AntennaCbk(GlobalRouter* grouter) : _grouter(grouter)
{
}
void AntennaCbk::inDbPostMoveInst(odb::dbInst* inst)
{
for (odb::dbITerm* iterm : inst->getITerms()) {
if (iterm->getNet() != nullptr && !iterm->getNet()->isSpecial())
_grouter->addDirtyNet(iterm->getNet());
}
}
} // namespace grt
<commit_msg>grt: refactor iterm->getNet()<commit_after>/////////////////////////////////////////////////////////////////////////////
//
// BSD 3-Clause License
//
// Copyright (c) 2019, University of California, San Diego.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder 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 "AntennaRepair.h"
#include <cmath>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "Net.h"
#include "Pin.h"
#include "grt/GlobalRouter.h"
#include "utl/Logger.h"
namespace grt {
using utl::GRT;
AntennaRepair::AntennaRepair(GlobalRouter* grouter,
ant::AntennaChecker* arc,
dpl::Opendp* opendp,
odb::dbDatabase* db,
utl::Logger* logger)
: _grouter(grouter), _arc(arc), _opendp(opendp), _db(db), _logger(logger)
{
_block = _db->getChip()->getBlock();
}
int AntennaRepair::checkAntennaViolations(NetRouteMap& routing,
int maxRoutingLayer,
odb::dbMTerm* diodeMTerm)
{
odb::dbTech* tech = _db->getTech();
_arc->load_antenna_rules();
std::map<int, odb::dbTechVia*> defaultVias
= _grouter->getDefaultVias(maxRoutingLayer);
for (auto net_route : routing) {
odb::dbNet* db_net = net_route.first;
GRoute& route = net_route.second;
odb::dbWire* wire = odb::dbWire::create(db_net);
if (wire != nullptr) {
odb::dbWireEncoder wireEncoder;
wireEncoder.begin(wire);
odb::dbWireType wireType = odb::dbWireType::ROUTED;
for (GSegment& seg : route) {
if (std::abs(seg.initLayer - seg.finalLayer) > 1) {
_logger->error(GRT, 68, "Global route segment not valid.");
}
int x1 = seg.initX;
int y1 = seg.initY;
int x2 = seg.finalX;
int y2 = seg.finalY;
int l1 = seg.initLayer;
int l2 = seg.finalLayer;
odb::dbTechLayer* currLayer = tech->findRoutingLayer(l1);
if (l1 == l2) { // Add wire
if (x1 == x2 && y1 == y2)
continue;
wireEncoder.newPath(currLayer, wireType);
wireEncoder.addPoint(x1, y1);
wireEncoder.addPoint(x2, y2);
} else { // Add via
int bottomLayer = (l1 < l2) ? l1 : l2;
wireEncoder.newPath(currLayer, wireType);
wireEncoder.addPoint(x1, y1);
wireEncoder.addTechVia(defaultVias[bottomLayer]);
}
}
wireEncoder.end();
odb::orderWires(db_net, false, false);
std::vector<ant::VINFO> netViol = _arc->get_net_antenna_violations(
db_net,
diodeMTerm->getMaster()->getConstName(),
diodeMTerm->getConstName());
if (!netViol.empty()) {
_antennaViolations[db_net] = netViol;
_grouter->addDirtyNet(db_net);
}
odb::dbWire::destroy(wire);
} else {
_logger->error(GRT, 221, "Cannot create wire for net {}.", db_net->getConstName());
}
}
_logger->info(GRT, 12, "Antenna violations: {}", _antennaViolations.size());
return _antennaViolations.size();
}
void AntennaRepair::fixAntennas(odb::dbMTerm* diodeMTerm)
{
int siteWidth = -1;
int cnt = 0;
r_tree fixedInsts;
auto rows = _block->getRows();
for (odb::dbRow* db_row : rows) {
odb::dbSite* site = db_row->getSite();
int site_width = site->getWidth();
if (siteWidth == -1) {
siteWidth = site_width;
}
if (siteWidth != site_width) {
_logger->warn(GRT, 27, "Design has rows with different site widths.");
}
}
deleteFillerCells();
setInstsPlacementStatus(odb::dbPlacementStatus::FIRM);
getFixedInstances(fixedInsts);
for (auto const& violation : _antennaViolations) {
odb::dbNet* net = violation.first;
for (int i = 0; i < violation.second.size(); i++) {
for (odb::dbITerm* sinkITerm : violation.second[i].iterms) {
odb::dbInst* sinkInst = sinkITerm->getInst();
for (int j = 0; j < violation.second[i].antenna_cell_nums; j++) {
std::string antennaInstName = "ANTENNA_" + std::to_string(cnt);
insertDiode(net,
diodeMTerm,
sinkInst,
sinkITerm,
antennaInstName,
siteWidth,
fixedInsts);
cnt++;
}
}
}
}
}
void AntennaRepair::legalizePlacedCells()
{
AntennaCbk* cbk = new AntennaCbk(_grouter);
cbk->addOwner(_block);
_opendp->detailedPlacement(0);
_opendp->checkPlacement(false);
cbk->removeOwner();
// After legalize placement, diodes and violated insts don't need to be FIRM
setInstsPlacementStatus(odb::dbPlacementStatus::PLACED);
}
void AntennaRepair::deleteFillerCells()
{
int fillerCnt = 0;
for (odb::dbInst* inst : _block->getInsts()) {
if (inst->getMaster()->getType() == odb::dbMasterType::CORE_SPACER) {
fillerCnt++;
odb::dbInst::destroy(inst);
}
}
if (fillerCnt > 0) {
_logger->info(GRT, 11, "Deleted {} filler cells.", fillerCnt);
}
}
void AntennaRepair::insertDiode(odb::dbNet* net,
odb::dbMTerm* diodeMTerm,
odb::dbInst* sinkInst,
odb::dbITerm* sinkITerm,
std::string antennaInstName,
int siteWidth,
r_tree& fixedInsts)
{
bool legallyPlaced = false;
bool placeAtLeft = true;
int leftOffset = 0;
int rightOffset = 0;
int offset;
std::string netName = net->getConstName();
odb::dbMaster* antennaMaster = diodeMTerm->getMaster();
int instLocX, instLocY, instWidth;
odb::dbBox* sinkBBox = sinkInst->getBBox();
instLocX = sinkBBox->xMin();
instLocY = sinkBBox->yMin();
instWidth = sinkBBox->xMax() - sinkBBox->xMin();
odb::dbOrientType instOrient = sinkInst->getOrient();
odb::dbInst* antennaInst
= odb::dbInst::create(_block, antennaMaster, antennaInstName.c_str());
odb::dbITerm* antennaITerm
= antennaInst->findITerm(diodeMTerm->getConstName());
odb::dbBox* antennaBBox = antennaInst->getBBox();
int antennaWidth = antennaBBox->xMax() - antennaBBox->xMin();
// Use R-tree to check if diode will not overlap or cause 1-site spacing with
// other cells
int leftPad = _opendp->padGlobalLeft();
int rightPad = _opendp->padGlobalRight();
std::vector<value> overlapInsts;
while (!legallyPlaced) {
if (placeAtLeft) {
offset = -(antennaWidth + leftOffset * siteWidth);
leftOffset++;
placeAtLeft = false;
} else {
offset = instWidth + rightOffset * siteWidth;
rightOffset++;
placeAtLeft = true;
}
antennaInst->setOrient(instOrient);
antennaInst->setLocation(instLocX + offset, instLocY);
odb::dbBox* instBox = antennaInst->getBBox();
box box(point(instBox->xMin() - ((leftPad + rightPad) * siteWidth) + 1,
instBox->yMin() + 1),
point(instBox->xMax() + ((leftPad + rightPad) * siteWidth) - 1,
instBox->yMax() - 1));
fixedInsts.query(bgi::intersects(box), std::back_inserter(overlapInsts));
odb::Rect coreArea;
_block->getCoreArea(coreArea);
if (overlapInsts.empty() && instBox->xMin() >= coreArea.xMin()
&& instBox->xMax() <= coreArea.xMax()) {
legallyPlaced = true;
}
overlapInsts.clear();
}
antennaInst->setPlacementStatus(odb::dbPlacementStatus::FIRM);
odb::dbITerm::connect(antennaITerm, net);
_diodeInsts.push_back(antennaInst);
// Add diode to the R-tree of fixed instances
int fixedInstId = fixedInsts.size();
odb::dbBox* instBox = antennaInst->getBBox();
box b(point(instBox->xMin(), instBox->yMin()),
point(instBox->xMax(), instBox->yMax()));
value v(b, fixedInstId);
fixedInsts.insert(v);
fixedInstId++;
}
void AntennaRepair::getFixedInstances(r_tree& fixedInsts)
{
int fixedInstId = 0;
for (odb::dbInst* inst : _block->getInsts()) {
if (inst->getPlacementStatus() == odb::dbPlacementStatus::FIRM) {
odb::dbBox* instBox = inst->getBBox();
box b(point(instBox->xMin(), instBox->yMin()),
point(instBox->xMax(), instBox->yMax()));
value v(b, fixedInstId);
fixedInsts.insert(v);
fixedInstId++;
}
}
}
void AntennaRepair::setInstsPlacementStatus(
odb::dbPlacementStatus placementStatus)
{
for (auto const& violation : _antennaViolations) {
for (int i = 0; i < violation.second.size(); i++) {
for (odb::dbITerm* sinkITerm : violation.second[i].iterms) {
sinkITerm->getInst()->setPlacementStatus(placementStatus);
}
}
}
for (odb::dbInst* diodeInst : _diodeInsts) {
diodeInst->setPlacementStatus(placementStatus);
}
}
AntennaCbk::AntennaCbk(GlobalRouter* grouter) : _grouter(grouter)
{
}
void AntennaCbk::inDbPostMoveInst(odb::dbInst* inst)
{
for (odb::dbITerm* iterm : inst->getITerms()) {
odb::dbNet* db_net = iterm->getNet();
if (db_net != nullptr && !db_net->isSpecial())
_grouter->addDirtyNet(iterm->getNet());
}
}
} // namespace grt
<|endoftext|>
|
<commit_before>/* This file is part of Ingen.
* Copyright (C) 2007-2009 David Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License alongCont
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cmath>
#include "interface/EngineInterface.hpp"
#include "shared/LV2URIMap.hpp"
#include "client/NodeModel.hpp"
#include "App.hpp"
#include "NodeControlWindow.hpp"
#include "GladeFactory.hpp"
#include "Controls.hpp"
#include "ControlPanel.hpp"
#include "PatchWindow.hpp"
using namespace std;
namespace Ingen {
namespace GUI {
/** Create a node control window and load a new ControlPanel for it.
*/
NodeControlWindow::NodeControlWindow(SharedPtr<NodeModel> node, uint32_t poly)
: _node(node)
, _position_stored(false)
, _x(0)
, _y(0)
{
assert(_node != NULL);
property_resizable() = true;
set_border_width(5);
set_title(_node->path().chop_scheme() + " Controls - Ingen");
Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference("warehouse_win");
xml->get_widget_derived("control_panel_vbox", _control_panel);
show_all_children();
_control_panel->reparent(*this);
_control_panel->init(_node, poly);
_control_panel->show();
resize();
_callback_enabled = true;
}
/** Create a node control window and with an existing ControlPanel.
*/
NodeControlWindow::NodeControlWindow(SharedPtr<NodeModel> node, ControlPanel* panel)
: _node(node)
, _control_panel(panel)
{
assert(_node);
property_resizable() = true;
set_border_width(5);
set_title(_node->path().chop_scheme() + " Controls - Ingen");
_control_panel->reparent(*this);
show_all_children();
resize();
_callback_enabled = true;
}
NodeControlWindow::~NodeControlWindow()
{
delete _control_panel;
}
void
NodeControlWindow::resize()
{
pair<int,int> controls_size = _control_panel->ideal_size();
int width = controls_size.first;
int height = controls_size.second;
if (height > property_screen().get_value()->get_height() - 64)
height = property_screen().get_value()->get_height() - 64;
if (width > property_screen().get_value()->get_width() - 64)
width = property_screen().get_value()->get_width() - 64;
Gtk::Window::resize(width, height);
}
void
NodeControlWindow::on_show()
{
for (NodeModel::Ports::const_iterator i = _node->ports().begin();
i != _node->ports().end(); ++i)
if ((*i)->is_input() && App::instance().can_control(i->get()))
App::instance().engine()->request_property((*i)->path(),
App::instance().uris().ingen_value);
if (_position_stored)
move(_x, _y);
Gtk::Window::on_show();
}
void
NodeControlWindow::on_hide()
{
_position_stored = true;
get_position(_x, _y);
Gtk::Window::on_hide();
}
} // namespace GUI
} // namespace Ingen
<commit_msg>Show human name instead of symbol in node control window (fix ticket #637).<commit_after>/* This file is part of Ingen.
* Copyright (C) 2007-2009 David Robillard <http://drobilla.net>
*
* Ingen 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.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License alongCont
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cmath>
#include "interface/EngineInterface.hpp"
#include "shared/LV2URIMap.hpp"
#include "client/NodeModel.hpp"
#include "App.hpp"
#include "NodeControlWindow.hpp"
#include "GladeFactory.hpp"
#include "Controls.hpp"
#include "ControlPanel.hpp"
#include "PatchWindow.hpp"
using namespace std;
namespace Ingen {
namespace GUI {
/** Create a node control window and load a new ControlPanel for it.
*/
NodeControlWindow::NodeControlWindow(SharedPtr<NodeModel> node, uint32_t poly)
: _node(node)
, _position_stored(false)
, _x(0)
, _y(0)
{
assert(_node != NULL);
property_resizable() = true;
set_border_width(5);
set_title(_node->plugin_model()->human_name() + " - Ingen");
Glib::RefPtr<Gnome::Glade::Xml> xml = GladeFactory::new_glade_reference("warehouse_win");
xml->get_widget_derived("control_panel_vbox", _control_panel);
show_all_children();
_control_panel->reparent(*this);
_control_panel->init(_node, poly);
_control_panel->show();
resize();
_callback_enabled = true;
}
/** Create a node control window and with an existing ControlPanel.
*/
NodeControlWindow::NodeControlWindow(SharedPtr<NodeModel> node, ControlPanel* panel)
: _node(node)
, _control_panel(panel)
{
assert(_node);
property_resizable() = true;
set_border_width(5);
set_title(_node->path().chop_scheme() + " Controls - Ingen");
_control_panel->reparent(*this);
show_all_children();
resize();
_callback_enabled = true;
}
NodeControlWindow::~NodeControlWindow()
{
delete _control_panel;
}
void
NodeControlWindow::resize()
{
pair<int,int> controls_size = _control_panel->ideal_size();
int width = controls_size.first;
int height = controls_size.second;
if (height > property_screen().get_value()->get_height() - 64)
height = property_screen().get_value()->get_height() - 64;
if (width > property_screen().get_value()->get_width() - 64)
width = property_screen().get_value()->get_width() - 64;
Gtk::Window::resize(width, height);
}
void
NodeControlWindow::on_show()
{
for (NodeModel::Ports::const_iterator i = _node->ports().begin();
i != _node->ports().end(); ++i)
if ((*i)->is_input() && App::instance().can_control(i->get()))
App::instance().engine()->request_property((*i)->path(),
App::instance().uris().ingen_value);
if (_position_stored)
move(_x, _y);
Gtk::Window::on_show();
}
void
NodeControlWindow::on_hide()
{
_position_stored = true;
get_position(_x, _y);
Gtk::Window::on_hide();
}
} // namespace GUI
} // namespace Ingen
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docruby.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-08-14 15:59:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#include <string.h> // fuer strchr()
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_UNICODETYPE_HDL
#include <com/sun/star/i18n/UnicodeType.hdl>
#endif
#ifndef _COM_SUN_STAR_I18N_WORDTYPE_HDL
#include <com/sun/star/i18n/WordType.hdl>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _MVSAVE_HXX
#include <mvsave.hxx> // Strukturen zum Sichern beim Move/Delete
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
#ifndef _RUBYLIST_HXX
#include <rubylist.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer die UndoIds
#endif
#ifndef _UNDOBJ_HXX
#include <undobj.hxx>
#endif
#ifndef _BREAKIT_HXX
#include <breakit.hxx>
#endif
#ifndef _CRSSKIP_HXX
#include <crsskip.hxx>
#endif
SV_IMPL_PTRARR( SwRubyList, SwRubyListEntryPtr )
using namespace ::com::sun::star::i18n;
/*
* Members in the list:
* - String - the orig text
* - SwFmtRuby - the ruby attribut
*
*
*/
USHORT SwDoc::FillRubyList( const SwPaM& rPam, SwRubyList& rList,
USHORT nMode )
{
const SwPaM *_pStartCrsr = (SwPaM*)rPam.GetNext(),
*__pStartCrsr = _pStartCrsr;
BOOL bCheckEmpty = &rPam != _pStartCrsr;
do {
const SwPosition* pStt = _pStartCrsr->Start(),
* pEnd = pStt == _pStartCrsr->GetPoint()
? _pStartCrsr->GetMark()
: _pStartCrsr->GetPoint();
if( !bCheckEmpty || ( pStt != pEnd && *pStt != *pEnd ))
{
SwPaM aPam( *pStt );
do {
SwRubyListEntry* pNew = new SwRubyListEntry;
if( pEnd != pStt )
{
aPam.SetMark();
*aPam.GetMark() = *pEnd;
}
if( _SelectNextRubyChars( aPam, *pNew, nMode ))
{
rList.Insert( pNew, rList.Count() );
aPam.DeleteMark();
}
else
{
delete pNew;
if( *aPam.GetPoint() < *pEnd )
{
// goto next paragraph
aPam.DeleteMark();
aPam.Move( fnMoveForward, fnGoNode );
}
else
break;
}
} while( 30 > rList.Count() && *aPam.GetPoint() < *pEnd );
}
} while( 30 > rList.Count() &&
(_pStartCrsr=(SwPaM *)_pStartCrsr->GetNext()) != __pStartCrsr );
return rList.Count();
}
USHORT SwDoc::SetRubyList( const SwPaM& rPam, const SwRubyList& rList,
USHORT nMode )
{
StartUndo( UNDO_SETRUBYATTR, NULL );
SvUShortsSort aDelArr;
aDelArr.Insert( RES_TXTATR_CJK_RUBY );
USHORT nListEntry = 0;
const SwPaM *_pStartCrsr = (SwPaM*)rPam.GetNext(),
*__pStartCrsr = _pStartCrsr;
BOOL bCheckEmpty = &rPam != _pStartCrsr;
do {
const SwPosition* pStt = _pStartCrsr->Start(),
* pEnd = pStt == _pStartCrsr->GetPoint()
? _pStartCrsr->GetMark()
: _pStartCrsr->GetPoint();
if( !bCheckEmpty || ( pStt != pEnd && *pStt != *pEnd ))
{
SwPaM aPam( *pStt );
do {
SwRubyListEntry aCheckEntry;
if( pEnd != pStt )
{
aPam.SetMark();
*aPam.GetMark() = *pEnd;
}
if( _SelectNextRubyChars( aPam, aCheckEntry, nMode ))
{
const SwRubyListEntry* pEntry = rList[ nListEntry++ ];
if( aCheckEntry.GetRubyAttr() != pEntry->GetRubyAttr() )
{
// set/reset the attribut
if( pEntry->GetRubyAttr().GetText().Len() )
Insert( aPam, pEntry->GetRubyAttr(), 0 );
else
ResetAttr( aPam, TRUE, &aDelArr );
}
if( aCheckEntry.GetText() != pEntry->GetText() &&
pEntry->GetText().Len() )
{
// text is changed, so replace the original
Replace( aPam, pEntry->GetText(), FALSE );
}
aPam.DeleteMark();
}
else
{
if( *aPam.GetPoint() < *pEnd )
{
// goto next paragraph
aPam.DeleteMark();
aPam.Move( fnMoveForward, fnGoNode );
}
else
{
const SwRubyListEntry* pEntry = rList[ nListEntry++ ];
// set/reset the attribut
if( pEntry->GetRubyAttr().GetText().Len() &&
pEntry->GetText().Len() )
{
Insert( aPam, pEntry->GetText(), true );
aPam.SetMark();
aPam.GetMark()->nContent -= pEntry->GetText().Len();
Insert( aPam, pEntry->GetRubyAttr(), SETATTR_DONTEXPAND );
}
else
break;
aPam.DeleteMark();
}
}
} while( nListEntry < rList.Count() && *aPam.GetPoint() < *pEnd );
}
} while( 30 > rList.Count() &&
(_pStartCrsr=(SwPaM *)_pStartCrsr->GetNext()) != __pStartCrsr );
EndUndo( UNDO_SETRUBYATTR, NULL );
return nListEntry;
}
BOOL SwDoc::_SelectNextRubyChars( SwPaM& rPam, SwRubyListEntry& rEntry,
USHORT nMode )
{
// Point must be the startposition, Mark is optional the end position
SwPosition* pPos = rPam.GetPoint();
const SwTxtNode* pTNd = pPos->nNode.GetNode().GetTxtNode();
const String* pTxt = &pTNd->GetTxt();
xub_StrLen nStart = pPos->nContent.GetIndex(), nEnd = pTxt->Len();
BOOL bHasMark = rPam.HasMark();
if( bHasMark )
{
// in the same node?
if( rPam.GetMark()->nNode == pPos->nNode )
{
// then use that end
xub_StrLen nTEnd = rPam.GetMark()->nContent.GetIndex();
if( nTEnd < nEnd )
nEnd = nTEnd;
}
rPam.DeleteMark();
}
// ----- search the start
// --- look where a ruby attribut starts
USHORT nHtIdx = USHRT_MAX;
const SwpHints* pHts = pTNd->GetpSwpHints();
const SwTxtAttr* pAttr = 0;
if( pHts )
{
const SwTxtAttr* pHt;
for( nHtIdx = 0; nHtIdx < pHts->Count(); ++nHtIdx )
if( RES_TXTATR_CJK_RUBY == ( pHt = (*pHts)[ nHtIdx ])->Which() &&
*pHt->GetAnyEnd() > nStart )
{
if( *pHt->GetStart() < nEnd )
{
pAttr = pHt;
if( !bHasMark && nStart > *pAttr->GetStart() )
{
nStart = *pAttr->GetStart();
pPos->nContent = nStart;
}
}
break;
}
}
if( !bHasMark && nStart && ( !pAttr || nStart != *pAttr->GetStart()) )
{
// skip to the word begin!
long nWordStt = pBreakIt->xBreak->getWordBoundary(
*pTxt, nStart,
pBreakIt->GetLocale( pTNd->GetLang( nStart )),
WordType::ANYWORD_IGNOREWHITESPACES,
TRUE ).startPos;
if( nWordStt < nStart && -1 != nWordStt )
{
nStart = (xub_StrLen)nWordStt;
pPos->nContent = nStart;
}
}
BOOL bAlphaNum = FALSE;
long nWordEnd = nEnd;
CharClass& rCC = GetAppCharClass();
while( nStart < nEnd )
{
if( pAttr && nStart == *pAttr->GetStart() )
{
pPos->nContent = nStart;
if( !rPam.HasMark() )
{
rPam.SetMark();
pPos->nContent = *pAttr->GetAnyEnd();
if( pPos->nContent.GetIndex() > nEnd )
pPos->nContent = nEnd;
rEntry.SetRubyAttr( pAttr->GetRuby() );
}
break;
}
sal_Int32 nChType = rCC.getType( *pTxt, nStart );
BOOL bIgnoreChar = FALSE, bIsAlphaNum = FALSE, bChkNxtWrd = FALSE;
switch( nChType )
{
case UnicodeType::UPPERCASE_LETTER:
case UnicodeType::LOWERCASE_LETTER:
case UnicodeType::TITLECASE_LETTER:
case UnicodeType::DECIMAL_DIGIT_NUMBER:
bChkNxtWrd = bIsAlphaNum = TRUE;
break;
case UnicodeType::SPACE_SEPARATOR:
case UnicodeType::CONTROL:
/*??*/ case UnicodeType::PRIVATE_USE:
case UnicodeType::START_PUNCTUATION:
case UnicodeType::END_PUNCTUATION:
bIgnoreChar = TRUE;
break;
case UnicodeType::OTHER_LETTER:
bChkNxtWrd = TRUE;
// no break!
// case UnicodeType::UNASSIGNED:
// case UnicodeType::MODIFIER_LETTER:
// case UnicodeType::NON_SPACING_MARK:
// case UnicodeType::ENCLOSING_MARK:
// case UnicodeType::COMBINING_SPACING_MARK:
// case UnicodeType::LETTER_NUMBER:
// case UnicodeType::OTHER_NUMBER:
// case UnicodeType::LINE_SEPARATOR:
// case UnicodeType::PARAGRAPH_SEPARATOR:
// case UnicodeType::FORMAT:
// case UnicodeType::SURROGATE:
// case UnicodeType::DASH_PUNCTUATION:
// case UnicodeType::CONNECTOR_PUNCTUATION:
///*?? */case UnicodeType::OTHER_PUNCTUATION:
//--> char '!' is to ignore!
// case UnicodeType::MATH_SYMBOL:
// case UnicodeType::CURRENCY_SYMBOL:
// case UnicodeType::MODIFIER_SYMBOL:
// case UnicodeType::OTHER_SYMBOL:
// case UnicodeType::INITIAL_PUNCTUATION:
// case UnicodeType::FINAL_PUNCTUATION:
default:
bIsAlphaNum = FALSE;
break;
}
if( rPam.HasMark() )
{
if( bIgnoreChar || bIsAlphaNum != bAlphaNum || nStart >= nWordEnd )
break;
}
else if( !bIgnoreChar )
{
rPam.SetMark();
bAlphaNum = bIsAlphaNum;
if( bChkNxtWrd && pBreakIt->xBreak.is() )
{
// search the end of this word
nWordEnd = pBreakIt->xBreak->getWordBoundary(
*pTxt, nStart,
pBreakIt->GetLocale( pTNd->GetLang( nStart )),
WordType::ANYWORD_IGNOREWHITESPACES,
TRUE ).endPos;
if( 0 > nWordEnd || nWordEnd > nEnd || nWordEnd == nStart )
nWordEnd = nEnd;
}
}
pTNd->GoNext( &pPos->nContent, CRSR_SKIP_CHARS );
nStart = pPos->nContent.GetIndex();
}
nStart = rPam.GetMark()->nContent.GetIndex();
rEntry.SetText( pTxt->Copy( nStart,
rPam.GetPoint()->nContent.GetIndex() - nStart ));
return rPam.HasMark();
}
SwRubyListEntry::~SwRubyListEntry()
{
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.2); FILE MERGED 2006/09/01 17:51:26 kaib 1.9.2.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docruby.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-16 20:54:30 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"
#include <string.h> // fuer strchr()
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_UNICODETYPE_HDL
#include <com/sun/star/i18n/UnicodeType.hdl>
#endif
#ifndef _COM_SUN_STAR_I18N_WORDTYPE_HDL
#include <com/sun/star/i18n/WordType.hdl>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _MVSAVE_HXX
#include <mvsave.hxx> // Strukturen zum Sichern beim Move/Delete
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _TXATBASE_HXX
#include <txatbase.hxx>
#endif
#ifndef _RUBYLIST_HXX
#include <rubylist.hxx>
#endif
#ifndef _PAM_HXX
#include <pam.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx> // fuer die UndoIds
#endif
#ifndef _UNDOBJ_HXX
#include <undobj.hxx>
#endif
#ifndef _BREAKIT_HXX
#include <breakit.hxx>
#endif
#ifndef _CRSSKIP_HXX
#include <crsskip.hxx>
#endif
SV_IMPL_PTRARR( SwRubyList, SwRubyListEntryPtr )
using namespace ::com::sun::star::i18n;
/*
* Members in the list:
* - String - the orig text
* - SwFmtRuby - the ruby attribut
*
*
*/
USHORT SwDoc::FillRubyList( const SwPaM& rPam, SwRubyList& rList,
USHORT nMode )
{
const SwPaM *_pStartCrsr = (SwPaM*)rPam.GetNext(),
*__pStartCrsr = _pStartCrsr;
BOOL bCheckEmpty = &rPam != _pStartCrsr;
do {
const SwPosition* pStt = _pStartCrsr->Start(),
* pEnd = pStt == _pStartCrsr->GetPoint()
? _pStartCrsr->GetMark()
: _pStartCrsr->GetPoint();
if( !bCheckEmpty || ( pStt != pEnd && *pStt != *pEnd ))
{
SwPaM aPam( *pStt );
do {
SwRubyListEntry* pNew = new SwRubyListEntry;
if( pEnd != pStt )
{
aPam.SetMark();
*aPam.GetMark() = *pEnd;
}
if( _SelectNextRubyChars( aPam, *pNew, nMode ))
{
rList.Insert( pNew, rList.Count() );
aPam.DeleteMark();
}
else
{
delete pNew;
if( *aPam.GetPoint() < *pEnd )
{
// goto next paragraph
aPam.DeleteMark();
aPam.Move( fnMoveForward, fnGoNode );
}
else
break;
}
} while( 30 > rList.Count() && *aPam.GetPoint() < *pEnd );
}
} while( 30 > rList.Count() &&
(_pStartCrsr=(SwPaM *)_pStartCrsr->GetNext()) != __pStartCrsr );
return rList.Count();
}
USHORT SwDoc::SetRubyList( const SwPaM& rPam, const SwRubyList& rList,
USHORT nMode )
{
StartUndo( UNDO_SETRUBYATTR, NULL );
SvUShortsSort aDelArr;
aDelArr.Insert( RES_TXTATR_CJK_RUBY );
USHORT nListEntry = 0;
const SwPaM *_pStartCrsr = (SwPaM*)rPam.GetNext(),
*__pStartCrsr = _pStartCrsr;
BOOL bCheckEmpty = &rPam != _pStartCrsr;
do {
const SwPosition* pStt = _pStartCrsr->Start(),
* pEnd = pStt == _pStartCrsr->GetPoint()
? _pStartCrsr->GetMark()
: _pStartCrsr->GetPoint();
if( !bCheckEmpty || ( pStt != pEnd && *pStt != *pEnd ))
{
SwPaM aPam( *pStt );
do {
SwRubyListEntry aCheckEntry;
if( pEnd != pStt )
{
aPam.SetMark();
*aPam.GetMark() = *pEnd;
}
if( _SelectNextRubyChars( aPam, aCheckEntry, nMode ))
{
const SwRubyListEntry* pEntry = rList[ nListEntry++ ];
if( aCheckEntry.GetRubyAttr() != pEntry->GetRubyAttr() )
{
// set/reset the attribut
if( pEntry->GetRubyAttr().GetText().Len() )
Insert( aPam, pEntry->GetRubyAttr(), 0 );
else
ResetAttr( aPam, TRUE, &aDelArr );
}
if( aCheckEntry.GetText() != pEntry->GetText() &&
pEntry->GetText().Len() )
{
// text is changed, so replace the original
Replace( aPam, pEntry->GetText(), FALSE );
}
aPam.DeleteMark();
}
else
{
if( *aPam.GetPoint() < *pEnd )
{
// goto next paragraph
aPam.DeleteMark();
aPam.Move( fnMoveForward, fnGoNode );
}
else
{
const SwRubyListEntry* pEntry = rList[ nListEntry++ ];
// set/reset the attribut
if( pEntry->GetRubyAttr().GetText().Len() &&
pEntry->GetText().Len() )
{
Insert( aPam, pEntry->GetText(), true );
aPam.SetMark();
aPam.GetMark()->nContent -= pEntry->GetText().Len();
Insert( aPam, pEntry->GetRubyAttr(), SETATTR_DONTEXPAND );
}
else
break;
aPam.DeleteMark();
}
}
} while( nListEntry < rList.Count() && *aPam.GetPoint() < *pEnd );
}
} while( 30 > rList.Count() &&
(_pStartCrsr=(SwPaM *)_pStartCrsr->GetNext()) != __pStartCrsr );
EndUndo( UNDO_SETRUBYATTR, NULL );
return nListEntry;
}
BOOL SwDoc::_SelectNextRubyChars( SwPaM& rPam, SwRubyListEntry& rEntry,
USHORT nMode )
{
// Point must be the startposition, Mark is optional the end position
SwPosition* pPos = rPam.GetPoint();
const SwTxtNode* pTNd = pPos->nNode.GetNode().GetTxtNode();
const String* pTxt = &pTNd->GetTxt();
xub_StrLen nStart = pPos->nContent.GetIndex(), nEnd = pTxt->Len();
BOOL bHasMark = rPam.HasMark();
if( bHasMark )
{
// in the same node?
if( rPam.GetMark()->nNode == pPos->nNode )
{
// then use that end
xub_StrLen nTEnd = rPam.GetMark()->nContent.GetIndex();
if( nTEnd < nEnd )
nEnd = nTEnd;
}
rPam.DeleteMark();
}
// ----- search the start
// --- look where a ruby attribut starts
USHORT nHtIdx = USHRT_MAX;
const SwpHints* pHts = pTNd->GetpSwpHints();
const SwTxtAttr* pAttr = 0;
if( pHts )
{
const SwTxtAttr* pHt;
for( nHtIdx = 0; nHtIdx < pHts->Count(); ++nHtIdx )
if( RES_TXTATR_CJK_RUBY == ( pHt = (*pHts)[ nHtIdx ])->Which() &&
*pHt->GetAnyEnd() > nStart )
{
if( *pHt->GetStart() < nEnd )
{
pAttr = pHt;
if( !bHasMark && nStart > *pAttr->GetStart() )
{
nStart = *pAttr->GetStart();
pPos->nContent = nStart;
}
}
break;
}
}
if( !bHasMark && nStart && ( !pAttr || nStart != *pAttr->GetStart()) )
{
// skip to the word begin!
long nWordStt = pBreakIt->xBreak->getWordBoundary(
*pTxt, nStart,
pBreakIt->GetLocale( pTNd->GetLang( nStart )),
WordType::ANYWORD_IGNOREWHITESPACES,
TRUE ).startPos;
if( nWordStt < nStart && -1 != nWordStt )
{
nStart = (xub_StrLen)nWordStt;
pPos->nContent = nStart;
}
}
BOOL bAlphaNum = FALSE;
long nWordEnd = nEnd;
CharClass& rCC = GetAppCharClass();
while( nStart < nEnd )
{
if( pAttr && nStart == *pAttr->GetStart() )
{
pPos->nContent = nStart;
if( !rPam.HasMark() )
{
rPam.SetMark();
pPos->nContent = *pAttr->GetAnyEnd();
if( pPos->nContent.GetIndex() > nEnd )
pPos->nContent = nEnd;
rEntry.SetRubyAttr( pAttr->GetRuby() );
}
break;
}
sal_Int32 nChType = rCC.getType( *pTxt, nStart );
BOOL bIgnoreChar = FALSE, bIsAlphaNum = FALSE, bChkNxtWrd = FALSE;
switch( nChType )
{
case UnicodeType::UPPERCASE_LETTER:
case UnicodeType::LOWERCASE_LETTER:
case UnicodeType::TITLECASE_LETTER:
case UnicodeType::DECIMAL_DIGIT_NUMBER:
bChkNxtWrd = bIsAlphaNum = TRUE;
break;
case UnicodeType::SPACE_SEPARATOR:
case UnicodeType::CONTROL:
/*??*/ case UnicodeType::PRIVATE_USE:
case UnicodeType::START_PUNCTUATION:
case UnicodeType::END_PUNCTUATION:
bIgnoreChar = TRUE;
break;
case UnicodeType::OTHER_LETTER:
bChkNxtWrd = TRUE;
// no break!
// case UnicodeType::UNASSIGNED:
// case UnicodeType::MODIFIER_LETTER:
// case UnicodeType::NON_SPACING_MARK:
// case UnicodeType::ENCLOSING_MARK:
// case UnicodeType::COMBINING_SPACING_MARK:
// case UnicodeType::LETTER_NUMBER:
// case UnicodeType::OTHER_NUMBER:
// case UnicodeType::LINE_SEPARATOR:
// case UnicodeType::PARAGRAPH_SEPARATOR:
// case UnicodeType::FORMAT:
// case UnicodeType::SURROGATE:
// case UnicodeType::DASH_PUNCTUATION:
// case UnicodeType::CONNECTOR_PUNCTUATION:
///*?? */case UnicodeType::OTHER_PUNCTUATION:
//--> char '!' is to ignore!
// case UnicodeType::MATH_SYMBOL:
// case UnicodeType::CURRENCY_SYMBOL:
// case UnicodeType::MODIFIER_SYMBOL:
// case UnicodeType::OTHER_SYMBOL:
// case UnicodeType::INITIAL_PUNCTUATION:
// case UnicodeType::FINAL_PUNCTUATION:
default:
bIsAlphaNum = FALSE;
break;
}
if( rPam.HasMark() )
{
if( bIgnoreChar || bIsAlphaNum != bAlphaNum || nStart >= nWordEnd )
break;
}
else if( !bIgnoreChar )
{
rPam.SetMark();
bAlphaNum = bIsAlphaNum;
if( bChkNxtWrd && pBreakIt->xBreak.is() )
{
// search the end of this word
nWordEnd = pBreakIt->xBreak->getWordBoundary(
*pTxt, nStart,
pBreakIt->GetLocale( pTNd->GetLang( nStart )),
WordType::ANYWORD_IGNOREWHITESPACES,
TRUE ).endPos;
if( 0 > nWordEnd || nWordEnd > nEnd || nWordEnd == nStart )
nWordEnd = nEnd;
}
}
pTNd->GoNext( &pPos->nContent, CRSR_SKIP_CHARS );
nStart = pPos->nContent.GetIndex();
}
nStart = rPam.GetMark()->nContent.GetIndex();
rEntry.SetText( pTxt->Copy( nStart,
rPam.GetPoint()->nContent.GetIndex() - nStart ));
return rPam.HasMark();
}
SwRubyListEntry::~SwRubyListEntry()
{
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: scroll.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: os $ $Date: 2002-06-28 12:08:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include "swtypes.hxx"
#include "swrect.hxx"
#include "scroll.hxx"
SwScrollbar::SwScrollbar( Window *pWin, int bHoriz ) :
ScrollBar( pWin,
WinBits( WB_3DLOOK | WB_HIDE | ( bHoriz ? WB_HSCROLL : WB_VSCROLL) ) ),
bHori( bHoriz ),
bAuto( FALSE ),
bThumbEnabled( TRUE ),
bVisible(FALSE),
bSizeSet(FALSE)
{
}
SwScrollbar::~SwScrollbar() {}
/*------------------------------------------------------------------------
Beschreibung: wird nach einer Aenderung der Dokumentgroesse gerufen, um den
Range des Scrollbars neu einzustellen.
------------------------------------------------------------------------*/
void SwScrollbar::DocSzChgd( const Size &rSize )
{
aDocSz = rSize;
SetRange( Range( 0, bHori ? rSize.Width() : rSize.Height()) );
const ULONG nVisSize = GetVisibleSize();
SetLineSize( nVisSize * 10 / 100 );
SetPageSize( nVisSize * 77 / 100 );
}
/*------------------------------------------------------------------------
Beschreibung: wird nach einer Veraenderung des sichtbaren Ausschnittes
gerufen.
------------------------------------------------------------------------*/
void SwScrollbar::ViewPortChgd( const Rectangle &rRect )
{
long nThumb, nVisible;
if( bHori )
{
nThumb = rRect.Left();
nVisible = rRect.GetWidth();
}
else
{
nThumb = rRect.Top();
nVisible = rRect.GetHeight();
}
SetVisibleSize( nVisible );
DocSzChgd(aDocSz);
if ( bThumbEnabled )
SetThumbPos( nThumb );
long nVis = GetVisibleSize();
long nLen = GetRange().Len();
if(bAuto)
AutoShow();
}
void SwScrollbar::EnableThumbPos( BOOL bEnable, const SwRect &rVisArea )
{
bThumbEnabled = bEnable;
if ( bEnable )
{
long nThumb = bHori ? rVisArea.Left() : rVisArea.Top();
SetThumbPos( nThumb );
}
}
/*-----------------10/21/97 02:48pm-----------------
--------------------------------------------------*/
void SwScrollbar::Show( BOOL bSet )
{
bVisible = bSet;
if( (!bSet || bSizeSet || !bAuto) && IsUpdateMode() )
ScrollBar::Show(bSet);
}
/*-----------------10/21/97 03:23pm-----------------
--------------------------------------------------*/
void SwScrollbar::SetPosSizePixel( const Point& rNewPos, const Size& rNewSize )
{
ScrollBar::SetPosSizePixel(rNewPos, rNewSize);
bSizeSet = TRUE;
if(bVisible)
Show();
}
/*-----------------10/21/97 04:47pm-----------------
--------------------------------------------------*/
void SwScrollbar::SetUpdateMode( BOOL bUpdate )
{
ScrollBar::SetUpdateMode( bUpdate );
if(bUpdate &&
bVisible != ScrollBar::IsVisible())
{
if(bAuto)
AutoShow();
else
ScrollBar::Show(bVisible);
}
}
/*-----------------14.04.98 11:38-------------------
--------------------------------------------------*/
void SwScrollbar::SetAuto(BOOL bSet)
{
if(bAuto != bSet)
{
bAuto = bSet;
// automatisch versteckt - dann anzeigen
if(!bAuto && bVisible && !ScrollBar::IsVisible())
Show(TRUE);
else if(bAuto)
AutoShow(); // oder automatisch verstecken
}
}
/*-----------------14.04.98 11:43-------------------
--------------------------------------------------*/
void SwScrollbar::AutoShow()
{
long nVis = GetVisibleSize();
long nLen = GetRange().Len();
{
if( nVis >= nLen - 1)
{
if(ScrollBar::IsVisible())
ScrollBar::Show(FALSE);
}
else if ( !ScrollBar::IsVisible() &&
(!bHori || nVis) ) //Optimierung fuer Browser.
//Horizontaler Scrollbar per
//default aus.
{
ScrollBar::Show(TRUE);
}
}
}
<commit_msg>#103358# no UI mirroring for horz scrollbars<commit_after>/*************************************************************************
*
* $RCSfile: scroll.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: ssa $ $Date: 2002-09-17 09:40:27 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include "swtypes.hxx"
#include "swrect.hxx"
#include "scroll.hxx"
SwScrollbar::SwScrollbar( Window *pWin, int bHoriz ) :
ScrollBar( pWin,
WinBits( WB_3DLOOK | WB_HIDE | ( bHoriz ? WB_HSCROLL : WB_VSCROLL) ) ),
bHori( bHoriz ),
bAuto( FALSE ),
bThumbEnabled( TRUE ),
bVisible(FALSE),
bSizeSet(FALSE)
{
// SSA: --- RTL --- no mirroring for horizontal scrollbars
if( bHoriz )
EnableRTL( FALSE );
}
SwScrollbar::~SwScrollbar() {}
/*------------------------------------------------------------------------
Beschreibung: wird nach einer Aenderung der Dokumentgroesse gerufen, um den
Range des Scrollbars neu einzustellen.
------------------------------------------------------------------------*/
void SwScrollbar::DocSzChgd( const Size &rSize )
{
aDocSz = rSize;
SetRange( Range( 0, bHori ? rSize.Width() : rSize.Height()) );
const ULONG nVisSize = GetVisibleSize();
SetLineSize( nVisSize * 10 / 100 );
SetPageSize( nVisSize * 77 / 100 );
}
/*------------------------------------------------------------------------
Beschreibung: wird nach einer Veraenderung des sichtbaren Ausschnittes
gerufen.
------------------------------------------------------------------------*/
void SwScrollbar::ViewPortChgd( const Rectangle &rRect )
{
long nThumb, nVisible;
if( bHori )
{
nThumb = rRect.Left();
nVisible = rRect.GetWidth();
}
else
{
nThumb = rRect.Top();
nVisible = rRect.GetHeight();
}
SetVisibleSize( nVisible );
DocSzChgd(aDocSz);
if ( bThumbEnabled )
SetThumbPos( nThumb );
long nVis = GetVisibleSize();
long nLen = GetRange().Len();
if(bAuto)
AutoShow();
}
void SwScrollbar::EnableThumbPos( BOOL bEnable, const SwRect &rVisArea )
{
bThumbEnabled = bEnable;
if ( bEnable )
{
long nThumb = bHori ? rVisArea.Left() : rVisArea.Top();
SetThumbPos( nThumb );
}
}
/*-----------------10/21/97 02:48pm-----------------
--------------------------------------------------*/
void SwScrollbar::Show( BOOL bSet )
{
bVisible = bSet;
if( (!bSet || bSizeSet || !bAuto) && IsUpdateMode() )
ScrollBar::Show(bSet);
}
/*-----------------10/21/97 03:23pm-----------------
--------------------------------------------------*/
void SwScrollbar::SetPosSizePixel( const Point& rNewPos, const Size& rNewSize )
{
ScrollBar::SetPosSizePixel(rNewPos, rNewSize);
bSizeSet = TRUE;
if(bVisible)
Show();
}
/*-----------------10/21/97 04:47pm-----------------
--------------------------------------------------*/
void SwScrollbar::SetUpdateMode( BOOL bUpdate )
{
ScrollBar::SetUpdateMode( bUpdate );
if(bUpdate &&
bVisible != ScrollBar::IsVisible())
{
if(bAuto)
AutoShow();
else
ScrollBar::Show(bVisible);
}
}
/*-----------------14.04.98 11:38-------------------
--------------------------------------------------*/
void SwScrollbar::SetAuto(BOOL bSet)
{
if(bAuto != bSet)
{
bAuto = bSet;
// automatisch versteckt - dann anzeigen
if(!bAuto && bVisible && !ScrollBar::IsVisible())
Show(TRUE);
else if(bAuto)
AutoShow(); // oder automatisch verstecken
}
}
/*-----------------14.04.98 11:43-------------------
--------------------------------------------------*/
void SwScrollbar::AutoShow()
{
long nVis = GetVisibleSize();
long nLen = GetRange().Len();
{
if( nVis >= nLen - 1)
{
if(ScrollBar::IsVisible())
ScrollBar::Show(FALSE);
}
else if ( !ScrollBar::IsVisible() &&
(!bHori || nVis) ) //Optimierung fuer Browser.
//Horizontaler Scrollbar per
//default aus.
{
ScrollBar::Show(TRUE);
}
}
}
<|endoftext|>
|
<commit_before>/*!
* \page StandardAirlineITTestSuite_cpp Command-Line Test to Demonstrate How To Extend StdAir BOM
* \code
*/
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost MPL
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE StdAirTest
#if BOOST_VERSION >= 103900
#include <boost/test/unit_test.hpp>
#else // BOOST_VERSION >= 103900
#include <boost/test/test_tools.hpp>
#include <boost/test/results_reporter.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/output_test_stream.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/detail/unit_test_parameters.hpp>
#endif // BOOST_VERSION >= 103900
// Boost Serialisation
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
// StdAir
#include <stdair/stdair_inventory_types.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
#include <stdair/basic/float_utils.hpp>
#include <stdair/bom/BomDisplay.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/factory/FacBom.hpp>
#include <stdair/factory/FacBomManager.hpp>
// StdAir Test Suite
#include <test/stdair/StdairTestLib.hpp>
#include <test/stdair/MPInventory.hpp>
namespace boost_utf = boost::unit_test;
#if BOOST_VERSION >= 103900
// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("StandardAirlineITTestSuite_utfresults.xml");
/**
* Configuration for the Boost Unit Test Framework (UTF)
*/
struct UnitTestConfig {
/** Constructor. */
UnitTestConfig() {
boost_utf::unit_test_log.set_stream (utfReportStream);
boost_utf::unit_test_log.set_format (boost_utf::XML);
boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
// boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
}
/** Destructor. */
~UnitTestConfig() {
}
};
// /////////////// Main: Unit Test Suite //////////////
// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);
// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)
/**
* Test the comparison of two floating point numbers, first the Boost way,
* then the Google way.
*/
BOOST_AUTO_TEST_CASE (float_comparison_test) {
float a = 0.2f;
a = 5*a;
const float b = 1.0f;
// Test the Boost way
BOOST_CHECK_MESSAGE (a == b, "The two floats (" << a << " and " << b
<< ") should be equal, but are not");
BOOST_CHECK_CLOSE (a, b, 0.0001);
// Test the Google way
const FloatingPoint<float> lhs (a), rhs (b);
BOOST_CHECK_MESSAGE (lhs.AlmostEquals (rhs),
"The two floats (" << a << " and " << b
<< ") should be equal, but are not");
}
/**
* Test MPL-based type handling, just as a proof-of-concept. It does
* not use StdAir BOM.
*/
BOOST_AUTO_TEST_CASE (mpl_structure_test) {
const stdair::ClassCode_T lBookingClassCodeA ("A");
const stdair_test::BookingClass lA (lBookingClassCodeA);
const stdair_test::Cabin lCabin (lA);
BOOST_CHECK_EQUAL (lCabin.toString(), lBookingClassCodeA);
BOOST_CHECK_MESSAGE (lCabin.toString() == lBookingClassCodeA,
"The cabin key, '" << lCabin.toString()
<< "' is not equal to '" << lBookingClassCodeA << "'");
// MPL
typedef boost::mpl::vector<stdair_test::BookingClass> MPL_BookingClass;
typedef boost::mpl::push_back<MPL_BookingClass,
stdair_test::Cabin>::type types;
if (boost::is_same<stdair_test::BookingClass,
stdair_test::Cabin::child>::value == false) {
BOOST_ERROR ("The two types mut be equal, but are not");
}
if (boost::is_same<boost::mpl::at_c<types, 1>::type,
stdair_test::Cabin>::value == false) {
BOOST_ERROR ("The type must be stdair_test::Cabin, but is not");
}
}
/**
* Test the initialisation of the Standard Airline IT base library.
*/
BOOST_AUTO_TEST_CASE (stdair_service_initialisation_test) {
// Output log File
const std::string lLogFilename ("StandardAirlineITTestSuite_init.log");
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the stdair BOM
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
stdair::STDAIR_Service stdairService (lLogParams);
// Retrieve (a reference on) the top of the BOM tree
stdair::BomRoot& lBomRoot = stdairService.getBomRoot();
// Retrieve the BomRoot key, and compare it to the expected one
const std::string& lBomRootKeyStr = lBomRoot.describeKey();
const std::string lBomRootString (" -- ROOT -- ");
// DEBUG
STDAIR_LOG_DEBUG ("The BOM root key is '" << lBomRootKeyStr
<< "'. It should be equal to '" << lBomRootString << "'");
BOOST_CHECK_EQUAL (lBomRootKeyStr, lBomRootString);
BOOST_CHECK_MESSAGE (lBomRootKeyStr == lBomRootString,
"The BOM root key, '" << lBomRootKeyStr
<< "', should be equal to '" << lBomRootString
<< "', but is not.");
// Build a sample BOM tree
stdairService.buildSampleBom();
// DEBUG: Display the whole BOM tree
const std::string& lCSVDump = stdairService.csvDisplay();
STDAIR_LOG_DEBUG (lCSVDump);
// Close the Log outputFile
logOutputFile.close();
}
/**
* Test the initialisation of Standard Airline IT BOM objects.
*/
BOOST_AUTO_TEST_CASE (bom_structure_instantiation_test) {
// Step 0.0: initialisation
// Create the root of the Bom tree (i.e., a BomRoot object)
stdair::BomRoot& lBomRoot =
stdair::FacBom<stdair::BomRoot>::instance().create();
// Step 0.1: Inventory level
// Create an Inventory (BA)
const stdair::AirlineCode_T lBAAirlineCode ("BA");
const stdair::InventoryKey lBAKey (lBAAirlineCode);
myprovider::Inventory& lBAInv =
stdair::FacBom<myprovider::Inventory>::instance().create (lBAKey);
stdair::FacBomManager::addToList (lBomRoot, lBAInv);
BOOST_CHECK_EQUAL (lBAInv.describeKey(), lBAAirlineCode);
BOOST_CHECK_MESSAGE (lBAInv.describeKey() == lBAAirlineCode,
"The inventory key, '" << lBAInv.describeKey()
<< "', should be equal to '" << lBAAirlineCode
<< "', but is not");
// Create an Inventory for AF
const stdair::AirlineCode_T lAFAirlineCode ("AF");
const stdair::InventoryKey lAFKey (lAFAirlineCode);
myprovider::Inventory& lAFInv =
stdair::FacBom<myprovider::Inventory>::instance().create (lAFKey);
stdair::FacBomManager::addToList (lBomRoot, lAFInv);
BOOST_CHECK_EQUAL (lAFInv.describeKey(), lAFAirlineCode);
BOOST_CHECK_MESSAGE (lAFInv.describeKey() == lAFAirlineCode,
"The inventory key, '" << lAFInv.describeKey()
<< "', should be equal to '" << lAFAirlineCode
<< "', but is not");
// Browse the inventories
const myprovider::InventoryList_T& lInventoryList =
stdair::BomManager::getList<myprovider::Inventory> (lBomRoot);
const std::string lInventoryKeyArray[2] = {lBAAirlineCode, lAFAirlineCode};
short idx = 0;
for (myprovider::InventoryList_T::const_iterator itInv =
lInventoryList.begin(); itInv != lInventoryList.end();
++itInv, ++idx) {
const myprovider::Inventory* lInv_ptr = *itInv;
BOOST_REQUIRE (lInv_ptr != NULL);
BOOST_CHECK_EQUAL (lInventoryKeyArray[idx], lInv_ptr->describeKey());
BOOST_CHECK_MESSAGE (lInventoryKeyArray[idx] == lInv_ptr->describeKey(),
"They inventory key, '" << lInventoryKeyArray[idx]
<< "', does not match that of the Inventory object: '"
<< lInv_ptr->describeKey() << "'");
}
}
/**
* Test the serialisation of Standard Airline IT BOM objects.
*/
BOOST_AUTO_TEST_CASE (bom_structure_serialisation_test) {
// Backup (thanks to Boost.Serialisation) file
const std::string lBackupFilename = "StandardAirlineITTestSuite_serial.txt";
// Output log File
const std::string lLogFilename ("StandardAirlineITTestSuite_serial.log");
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the stdair BOM
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
stdair::STDAIR_Service stdairService (lLogParams);
// Build a sample BOM tree
stdairService.buildSampleBom();
// DEBUG: Display the whole BOM tree
const std::string& lCSVDump = stdairService.csvDisplay();
STDAIR_LOG_DEBUG (lCSVDump);
// Clone the persistent BOM
stdairService.clonePersistentBom ();
// Retrieve (a reference on) the top of the BOM tree
stdair::BomRoot& lBomRoot = stdairService.getBomRoot();
// Retrieve the BomRoot key, and compare it to the expected one
const std::string lBAInvKeyStr ("BA");
stdair::Inventory* lBAInv_ptr = lBomRoot.getInventory (lBAInvKeyStr);
// DEBUG
STDAIR_LOG_DEBUG ("There should be an Inventory object corresponding to the '"
<< lBAInvKeyStr << "' key.");
BOOST_REQUIRE_MESSAGE (lBAInv_ptr != NULL,
"An Inventory object should exist with the key, '"
<< lBAInvKeyStr << "'.");
// create and open a character archive for output
std::ofstream ofs (lBackupFilename.c_str());
// save data to archive
{
boost::archive::text_oarchive oa (ofs);
// write class instance to archive
oa << lBomRoot;
// archive and stream closed when destructors are called
}
// ... some time later restore the class instance to its orginal state
stdair::BomRoot& lRestoredBomRoot =
stdair::FacBom<stdair::BomRoot>::instance().create();
{
// create and open an archive for input
std::ifstream ifs (lBackupFilename.c_str());
boost::archive::text_iarchive ia(ifs);
// read class state from archive
ia >> lRestoredBomRoot;
// archive and stream closed when destructors are called
}
// DEBUG: Display the whole BOM tree
std::ostringstream oRestoredCSVDumpStr;
stdair::BomDisplay::csvDisplay (oRestoredCSVDumpStr, lRestoredBomRoot);
STDAIR_LOG_DEBUG (oRestoredCSVDumpStr.str());
// Retrieve the BomRoot key, and compare it to the expected one
const std::string& lBomRootKeyStr = lRestoredBomRoot.describeKey();
const std::string lBomRootString (" -- ROOT -- ");
// DEBUG
STDAIR_LOG_DEBUG ("The BOM root key is '" << lBomRootKeyStr
<< "'. It should be equal to '" << lBomRootString << "'");
BOOST_CHECK_EQUAL (lBomRootKeyStr, lBomRootString);
BOOST_CHECK_MESSAGE (lBomRootKeyStr == lBomRootString,
"The BOM root key, '" << lBomRootKeyStr
<< "', should be equal to '" << lBomRootString
<< "', but is not.");
// Retrieve the Inventory
stdair::Inventory* lRestoredBAInv_ptr =
lRestoredBomRoot.getInventory (lBAInvKeyStr);
// DEBUG
STDAIR_LOG_DEBUG ("There should be an Inventory object corresponding to the '"
<< lBAInvKeyStr << "' key.");
BOOST_CHECK_MESSAGE (lRestoredBAInv_ptr != NULL,
"An Inventory object should exist with the key, '"
<< lBAInvKeyStr << "'.");
// Close the Log outputFile
logOutputFile.close();
}
// End the test suite
BOOST_AUTO_TEST_SUITE_END()
#else // BOOST_VERSION >= 103900
boost_utf::test_suite* init_unit_test_suite (int, char* []) {
boost_utf::test_suite* test = BOOST_TEST_SUITE ("Unit test example 1");
return test;
}
#endif // BOOST_VERSION >= 103900
/*!
* \endcode
*/
<commit_msg>[Test] Added a test to check the cloning process of Standard Airline IT BOM objects.<commit_after>/*!
* \page StandardAirlineITTestSuite_cpp Command-Line Test to Demonstrate How To Extend StdAir BOM
* \code
*/
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <sstream>
#include <fstream>
#include <string>
// Boost MPL
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/type_traits/is_same.hpp>
// Boost Unit Test Framework (UTF)
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE StdAirTest
#if BOOST_VERSION >= 103900
#include <boost/test/unit_test.hpp>
#else // BOOST_VERSION >= 103900
#include <boost/test/test_tools.hpp>
#include <boost/test/results_reporter.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/output_test_stream.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/detail/unit_test_parameters.hpp>
#endif // BOOST_VERSION >= 103900
// Boost Serialisation
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
// StdAir
#include <stdair/stdair_inventory_types.hpp>
#include <stdair/service/Logger.hpp>
#include <stdair/STDAIR_Service.hpp>
#include <stdair/basic/float_utils.hpp>
#include <stdair/bom/BomDisplay.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/BomManager.hpp>
#include <stdair/factory/FacBom.hpp>
#include <stdair/factory/FacBomManager.hpp>
// StdAir Test Suite
#include <test/stdair/StdairTestLib.hpp>
#include <test/stdair/MPInventory.hpp>
namespace boost_utf = boost::unit_test;
#if BOOST_VERSION >= 103900
// (Boost) Unit Test XML Report
std::ofstream utfReportStream ("StandardAirlineITTestSuite_utfresults.xml");
/**
* Configuration for the Boost Unit Test Framework (UTF)
*/
struct UnitTestConfig {
/** Constructor. */
UnitTestConfig() {
boost_utf::unit_test_log.set_stream (utfReportStream);
boost_utf::unit_test_log.set_format (boost_utf::XML);
boost_utf::unit_test_log.set_threshold_level (boost_utf::log_test_units);
// boost_utf::unit_test_log.set_threshold_level (boost_utf::log_successful_tests);
}
/** Destructor. */
~UnitTestConfig() {
}
};
// /////////////// Main: Unit Test Suite //////////////
// Set the UTF configuration (re-direct the output to a specific file)
BOOST_GLOBAL_FIXTURE (UnitTestConfig);
// Start the test suite
BOOST_AUTO_TEST_SUITE (master_test_suite)
/**
* Test the comparison of two floating point numbers, first the Boost way,
* then the Google way.
*/
BOOST_AUTO_TEST_CASE (float_comparison_test) {
float a = 0.2f;
a = 5*a;
const float b = 1.0f;
// Test the Boost way
BOOST_CHECK_MESSAGE (a == b, "The two floats (" << a << " and " << b
<< ") should be equal, but are not");
BOOST_CHECK_CLOSE (a, b, 0.0001);
// Test the Google way
const FloatingPoint<float> lhs (a), rhs (b);
BOOST_CHECK_MESSAGE (lhs.AlmostEquals (rhs),
"The two floats (" << a << " and " << b
<< ") should be equal, but are not");
}
/**
* Test MPL-based type handling, just as a proof-of-concept. It does
* not use StdAir BOM.
*/
BOOST_AUTO_TEST_CASE (mpl_structure_test) {
const stdair::ClassCode_T lBookingClassCodeA ("A");
const stdair_test::BookingClass lA (lBookingClassCodeA);
const stdair_test::Cabin lCabin (lA);
BOOST_CHECK_EQUAL (lCabin.toString(), lBookingClassCodeA);
BOOST_CHECK_MESSAGE (lCabin.toString() == lBookingClassCodeA,
"The cabin key, '" << lCabin.toString()
<< "' is not equal to '" << lBookingClassCodeA << "'");
// MPL
typedef boost::mpl::vector<stdair_test::BookingClass> MPL_BookingClass;
typedef boost::mpl::push_back<MPL_BookingClass,
stdair_test::Cabin>::type types;
if (boost::is_same<stdair_test::BookingClass,
stdair_test::Cabin::child>::value == false) {
BOOST_ERROR ("The two types mut be equal, but are not");
}
if (boost::is_same<boost::mpl::at_c<types, 1>::type,
stdair_test::Cabin>::value == false) {
BOOST_ERROR ("The type must be stdair_test::Cabin, but is not");
}
}
/**
* Test the initialisation of the Standard Airline IT base library.
*/
BOOST_AUTO_TEST_CASE (stdair_service_initialisation_test) {
// Output log File
const std::string lLogFilename ("StandardAirlineITTestSuite_init.log");
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the stdair BOM
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
stdair::STDAIR_Service stdairService (lLogParams);
// Retrieve (a reference on) the top of the persistent BOM tree
stdair::BomRoot& lPersistentBomRoot = stdairService.getPersistentBomRoot();
// Retrieve the BomRoot key, and compare it to the expected one
const std::string& lBomRootKeyStr = lPersistentBomRoot.describeKey();
const std::string lBomRootString (" -- ROOT -- ");
// DEBUG
STDAIR_LOG_DEBUG ("The BOM root key is '" << lBomRootKeyStr
<< "'. It should be equal to '" << lBomRootString << "'");
BOOST_CHECK_EQUAL (lBomRootKeyStr, lBomRootString);
BOOST_CHECK_MESSAGE (lBomRootKeyStr == lBomRootString,
"The BOM root key, '" << lBomRootKeyStr
<< "', should be equal to '" << lBomRootString
<< "', but is not.");
// Build a sample BOM tree
stdairService.buildSampleBom();
// DEBUG: Display the whole BOM tree
const std::string& lCSVDump = stdairService.csvDisplay(lPersistentBomRoot);
STDAIR_LOG_DEBUG (lCSVDump);
// Close the Log outputFile
logOutputFile.close();
}
/**
* Test the initialisation of Standard Airline IT BOM objects.
*/
BOOST_AUTO_TEST_CASE (bom_structure_instantiation_test) {
// Step 0.0: initialisation
// Create the root of a Bom tree (i.e., a BomRoot object)
stdair::BomRoot& lBomRoot =
stdair::FacBom<stdair::BomRoot>::instance().create();
// Step 0.1: Inventory level
// Create an Inventory (BA)
const stdair::AirlineCode_T lBAAirlineCode ("BA");
const stdair::InventoryKey lBAKey (lBAAirlineCode);
myprovider::Inventory& lBAInv =
stdair::FacBom<myprovider::Inventory>::instance().create (lBAKey);
stdair::FacBomManager::addToList (lBomRoot, lBAInv);
BOOST_CHECK_EQUAL (lBAInv.describeKey(), lBAAirlineCode);
BOOST_CHECK_MESSAGE (lBAInv.describeKey() == lBAAirlineCode,
"The inventory key, '" << lBAInv.describeKey()
<< "', should be equal to '" << lBAAirlineCode
<< "', but is not");
// Create an Inventory for AF
const stdair::AirlineCode_T lAFAirlineCode ("AF");
const stdair::InventoryKey lAFKey (lAFAirlineCode);
myprovider::Inventory& lAFInv =
stdair::FacBom<myprovider::Inventory>::instance().create (lAFKey);
stdair::FacBomManager::addToList (lBomRoot, lAFInv);
BOOST_CHECK_EQUAL (lAFInv.describeKey(), lAFAirlineCode);
BOOST_CHECK_MESSAGE (lAFInv.describeKey() == lAFAirlineCode,
"The inventory key, '" << lAFInv.describeKey()
<< "', should be equal to '" << lAFAirlineCode
<< "', but is not");
// Browse the inventories
const myprovider::InventoryList_T& lInventoryList =
stdair::BomManager::getList<myprovider::Inventory> (lBomRoot);
const std::string lInventoryKeyArray[2] = {lBAAirlineCode, lAFAirlineCode};
short idx = 0;
for (myprovider::InventoryList_T::const_iterator itInv =
lInventoryList.begin(); itInv != lInventoryList.end();
++itInv, ++idx) {
const myprovider::Inventory* lInv_ptr = *itInv;
BOOST_REQUIRE (lInv_ptr != NULL);
BOOST_CHECK_EQUAL (lInventoryKeyArray[idx], lInv_ptr->describeKey());
BOOST_CHECK_MESSAGE (lInventoryKeyArray[idx] == lInv_ptr->describeKey(),
"They inventory key, '" << lInventoryKeyArray[idx]
<< "', does not match that of the Inventory object: '"
<< lInv_ptr->describeKey() << "'");
}
}
/**
* Test the serialisation of Standard Airline IT BOM objects.
*/
BOOST_AUTO_TEST_CASE (bom_structure_serialisation_test) {
// Backup (thanks to Boost.Serialisation) file
const std::string lBackupFilename = "StandardAirlineITTestSuite_serial.txt";
// Output log File
const std::string lLogFilename ("StandardAirlineITTestSuite_serial.log");
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the stdair BOM
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
stdair::STDAIR_Service stdairService (lLogParams);
// Build a sample BOM tree
stdairService.buildSampleBom();
// Retrieve (a reference on) the top of the persistent BOM tree
stdair::BomRoot& lPersistentBomRoot = stdairService.getPersistentBomRoot();
// DEBUG: Display the whole BOM tree
const std::string& lCSVDump = stdairService.csvDisplay(lPersistentBomRoot);
STDAIR_LOG_DEBUG (lCSVDump);
// Clone the persistent BOM
stdairService.clonePersistentBom ();
// Retrieve the BomRoot key, and compare it to the expected one
const std::string lBAInvKeyStr ("BA");
stdair::Inventory* lBAInv_ptr =
lPersistentBomRoot.getInventory (lBAInvKeyStr);
// DEBUG
STDAIR_LOG_DEBUG ("There should be an Inventory object corresponding to the '"
<< lBAInvKeyStr << "' key.");
BOOST_REQUIRE_MESSAGE (lBAInv_ptr != NULL,
"An Inventory object should exist with the key, '"
<< lBAInvKeyStr << "'.");
// create and open a character archive for output
std::ofstream ofs (lBackupFilename.c_str());
// save data to archive
{
boost::archive::text_oarchive oa (ofs);
// write class instance to archive
oa << lPersistentBomRoot;
// archive and stream closed when destructors are called
}
// ... some time later restore the class instance to its orginal state
stdair::BomRoot& lRestoredBomRoot =
stdair::FacBom<stdair::BomRoot>::instance().create();
{
// create and open an archive for input
std::ifstream ifs (lBackupFilename.c_str());
boost::archive::text_iarchive ia(ifs);
// read class state from archive
ia >> lRestoredBomRoot;
// archive and stream closed when destructors are called
}
// DEBUG: Display the whole restored BOM tree
const std::string& lRestoredCSVDump =
stdairService.csvDisplay(lRestoredBomRoot);
STDAIR_LOG_DEBUG (lRestoredCSVDump);
// Retrieve the BomRoot key, and compare it to the expected one
const std::string& lBomRootKeyStr = lRestoredBomRoot.describeKey();
const std::string lBomRootString (" -- ROOT -- ");
// DEBUG
STDAIR_LOG_DEBUG ("The BOM root key is '" << lBomRootKeyStr
<< "'. It should be equal to '" << lBomRootString << "'");
BOOST_CHECK_EQUAL (lBomRootKeyStr, lBomRootString);
BOOST_CHECK_MESSAGE (lBomRootKeyStr == lBomRootString,
"The BOM root key, '" << lBomRootKeyStr
<< "', should be equal to '" << lBomRootString
<< "', but is not.");
// Retrieve the Inventory
stdair::Inventory* lRestoredBAInv_ptr =
lRestoredBomRoot.getInventory (lBAInvKeyStr);
// DEBUG
STDAIR_LOG_DEBUG ("There should be an Inventory object corresponding to the '"
<< lBAInvKeyStr << "' key in the restored BOM root.");
BOOST_CHECK_MESSAGE (lRestoredBAInv_ptr != NULL,
"An Inventory object should exist with the key, '"
<< lBAInvKeyStr << "' in the restored BOM root.");
// Close the Log outputFile
logOutputFile.close();
}
/**
* Test the clone of Standard Airline IT BOM objects.
*/
BOOST_AUTO_TEST_CASE (bom_structure_clone_test) {
// Output log File
const std::string lLogFilename ("StandardAirlineITTestSuite_clone.log");
// Set the log parameters
std::ofstream logOutputFile;
// Open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the stdair BOM
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
stdair::STDAIR_Service stdairService (lLogParams);
// Build a sample BOM tree
stdairService.buildSampleBom();
// Retrieve (a constant reference on) the top of the persistent BOM tree
const stdair::BomRoot& lPersistentBomRoot =
stdairService.getPersistentBomRoot();
// DEBUG: Display the whole persistent BOM tree
const std::string& lCSVDump = stdairService.csvDisplay(lPersistentBomRoot);
STDAIR_LOG_DEBUG ("Display the persistent BOM tree.");
STDAIR_LOG_DEBUG (lCSVDump);
// Retrieve (a reference on) the top of the clone BOM tree
stdair::BomRoot& lCloneBomRoot = stdairService.getBomRoot();
// DEBUG: Display the clone BOM tree before the clone process.
const std::string& lBeforeCloneCSVDump =
stdairService.csvDisplay(lCloneBomRoot);
STDAIR_LOG_DEBUG ("Display the clone BOM tree before the clone process.");
STDAIR_LOG_DEBUG (lBeforeCloneCSVDump);
// Clone the persistent BOM
stdairService.clonePersistentBom ();
// DEBUG: Display the clone BOM tree after the clone process.
const std::string& lAfterCloneCSVDump =
stdairService.csvDisplay(lCloneBomRoot);
STDAIR_LOG_DEBUG ("Display the clone BOM tree after the clone process.");
STDAIR_LOG_DEBUG (lAfterCloneCSVDump);
// Retrieve the clone BomRoot key, and compare it to the persistent BomRoot
// key.
const std::string& lCloneBomRootKeyStr = lCloneBomRoot.describeKey();
const std::string& lPersistentBomRootKeyStr =
lPersistentBomRoot.describeKey();
// DEBUG
STDAIR_LOG_DEBUG ("The clone BOM root key is '" << lCloneBomRootKeyStr
<< "'. It should be equal to '"
<< lPersistentBomRootKeyStr << "'");
BOOST_CHECK_EQUAL (lCloneBomRootKeyStr, lPersistentBomRootKeyStr);
BOOST_CHECK_MESSAGE (lCloneBomRootKeyStr == lPersistentBomRootKeyStr,
"The clone BOM root key, '" << lCloneBomRootKeyStr
<< "', should be equal to '" << lPersistentBomRootKeyStr
<< "', but is not.");
// Retrieve the BA inventory in the clone BOM root
const std::string lBAInvKeyStr ("BA");
stdair::Inventory* lCloneBAInv_ptr =
lCloneBomRoot.getInventory (lBAInvKeyStr);
// DEBUG
STDAIR_LOG_DEBUG ("There should be an Inventory object corresponding to the '"
<< lBAInvKeyStr << "' key in the clone BOM root.");
BOOST_CHECK_MESSAGE (lCloneBAInv_ptr != NULL,
"An Inventory object should exist with the key, '"
<< lBAInvKeyStr << "' in the clone BOM root.");
// Close the Log outputFile
logOutputFile.close();
}
// End the test suite
BOOST_AUTO_TEST_SUITE_END()
#else // BOOST_VERSION >= 103900
boost_utf::test_suite* init_unit_test_suite (int, char* []) {
boost_utf::test_suite* test = BOOST_TEST_SUITE ("Unit test example 1");
return test;
}
#endif // BOOST_VERSION >= 103900
/*!
* \endcode
*/
<|endoftext|>
|
<commit_before>/**
* \file demoFunctionApproximatorTraining.cpp
* \author Freek Stulp
* \brief Demonstrates how to train all functionapproximators with 1D and 2D data.
*
* \ingroup Demos
* \ingroup FunctionApproximators
*
* This file is part of DmpBbo, a set of libraries and programs for the
* black-box optimization of dynamical movement primitives.
* Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
*
* DmpBbo 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 of the License, or
* (at your option) any later version.
*
* DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <ctime>
#include <boost/filesystem.hpp>
#include "functionapproximators/FunctionApproximator.hpp"
#include "functionapproximators/MetaParametersLWR.hpp"
#include "functionapproximators/FunctionApproximatorLWR.hpp"
#include "functionapproximators/MetaParametersGMR.hpp"
#include "functionapproximators/FunctionApproximatorGMR.hpp"
#include "functionapproximators/MetaParametersRRRFF.hpp"
#include "functionapproximators/FunctionApproximatorRRRFF.hpp"
#include "functionapproximators/MetaParametersGPR.hpp"
#include "functionapproximators/FunctionApproximatorGPR.hpp"
#include "functionapproximators/MetaParametersRBFN.hpp"
#include "functionapproximators/FunctionApproximatorRBFN.hpp"
#ifdef USE_LWPR
#include "functionapproximators/MetaParametersLWPR.hpp"
#include "functionapproximators/FunctionApproximatorLWPR.hpp"
#endif // USE_LWPR
//#include "getFunctionApproximatorsVector.hpp"
#include "targetFunction.hpp"
using namespace std;
using namespace Eigen;
using namespace DmpBbo;
FunctionApproximator* getFunctionApproximatorByName(std::string name, int input_dim)
{
FunctionApproximator* fa = NULL;
if (name.compare("LWR")==0)
{
// Locally Weighted Regression
double intersection = 0.6;
Eigen::VectorXi num_rfs_per_dim = Eigen::VectorXi::Constant(input_dim,9);
if (input_dim==2) {
num_rfs_per_dim[0] = 7;
num_rfs_per_dim[1] = 5;
}
double regularization = 0.0;
MetaParametersLWR* meta_params = new MetaParametersLWR(input_dim,num_rfs_per_dim,intersection,regularization);
fa = new FunctionApproximatorLWR(meta_params);
}
else if (name.compare("GMR")==0)
{
// Gaussian Mixture Regression
int number_of_gaussians = 10;
if (input_dim==2) number_of_gaussians = 10;
MetaParametersGMR* meta_params = new MetaParametersGMR(input_dim,number_of_gaussians);
fa = new FunctionApproximatorGMR(meta_params);
}
else if (name.compare("RRRFF")==0)
{
// RRRFF
int number_of_basis_functions=18;
if (input_dim==2) number_of_basis_functions = 100;
double regularization=0.2;
double gamma=5;
MetaParametersRRRFF* meta_params = new MetaParametersRRRFF(input_dim,number_of_basis_functions,regularization,gamma);
fa = new FunctionApproximatorRRRFF(meta_params);
}
else if (name.compare("RBFN")==0)
{
// Radial Basis Function Network
double intersection = 0.7;
int n_rfs = 9;
if (input_dim==2) n_rfs = 5;
Eigen::VectorXi num_rfs_per_dim = Eigen::VectorXi::Constant(input_dim,n_rfs);
double regularization = 0.0;
MetaParametersRBFN* meta_params = new MetaParametersRBFN(input_dim,num_rfs_per_dim,intersection,regularization);
fa = new FunctionApproximatorRBFN(meta_params);
}
else if (name.compare("GPR")==0)
{
// Gaussian Process Regression
double maximum_covariance = 1.1*1.1;
double length = 0.1;
if (input_dim==2)
{
maximum_covariance = 0.1*0.1;
length = 0.2;
}
MetaParametersGPR* meta_params = new MetaParametersGPR(input_dim,maximum_covariance,length);
fa = new FunctionApproximatorGPR(meta_params);
}
else if (name.compare("LWPR")==0)
{
// Locally Weighted Projection Regression
#ifdef USE_LWPR
double w_gen=0.2;
double w_prune=0.8;
bool update_D=true;
double init_alpha=0.1;
double penalty=0.005;
Eigen::VectorXd init_D=Eigen::VectorXd::Constant(input_dim,200);
MetaParametersLWPR* meta_params = new MetaParametersLWPR(input_dim,init_D,w_gen,w_prune,update_D,init_alpha,penalty);
fa = new FunctionApproximatorLWPR(dynamic_cast<MetaParametersLWPR*>(meta_params));
#else
std::cerr << __FILE__ << ":" << __LINE__ << ":";
std::cerr << "Sorry, LWPR is not available. Is it installed? Returning NULL." << std::endl;
return NULL;
#endif // USE_LWPR
}
if (fa==NULL)
{
std::cerr << __FILE__ << ":" << __LINE__ << ":";
std::cerr << "Function approximator with name '" << name << "' is unknown. Returning NULL." << std::endl;
}
return fa;
}
/** Compute mean absolute error for each column of two matrices.
* \param[in] mat1 First matrix of data
* \param[in] mat2 Second matrix of data
* \return Mean absolute error between the matrices (one value for each column)
*/
VectorXd meanAbsoluteErrorPerOutputDimension(const MatrixXd& mat1, const MatrixXd& mat2)
{
MatrixXd abs_error = (mat1.array()-mat2.array()).abs();
VectorXd mean_abs_error_per_output_dim = abs_error.colwise().mean();
cout << fixed << setprecision(5);
cout << " Mean absolute error ";
if (mean_abs_error_per_output_dim.size()>1) cout << " (per dimension)";
cout << ": " << mean_abs_error_per_output_dim.transpose();
cout << " \t(range of target data is " << mat1.colwise().maxCoeff().array()-mat1.colwise().minCoeff().array() << ")" << endl;
return mean_abs_error_per_output_dim;
}
int main(int n_args, char** args)
{
// First argument may be optional directory to write data to
string directory;
if (n_args>1)
directory = string(args[1]);
vector<string> fa_names;
if (n_args>2)
{
for (int aa=2; aa<n_args; aa++)
fa_names.push_back(string(args[aa]));
}
else
{
fa_names.push_back("LWR");
fa_names.push_back("RRRFF");
fa_names.push_back("LWPR");
fa_names.push_back("GMR");
}
for (int n_input_dims=1; n_input_dims<=2; n_input_dims++)
{
// Generate training data
VectorXi n_samples_per_dim = VectorXi::Constant(1,30); // 25
if (n_input_dims==2)
n_samples_per_dim = VectorXi::Constant(2,10); // 2,25
MatrixXd inputs, targets, outputs;
targetFunction(n_samples_per_dim,inputs,targets);
// Add some noise
//targets = targets + 0.1*VectorXd::Random(targets.rows(),targets.cols());
for (unsigned int i_name=0; i_name<fa_names.size(); i_name++)
{
FunctionApproximator* cur_fa = getFunctionApproximatorByName(fa_names[i_name],n_input_dims);
if (cur_fa==NULL)
continue;
string save_directory;
if (!directory.empty())
save_directory = directory+"/"+fa_names[i_name]+"_"+(n_input_dims==1?"1D":"2D");
bool overwrite = true;
cout << "Training " << cur_fa->getName() << " on " << n_input_dims << "D data...\t";
cur_fa->train(inputs,targets,save_directory,overwrite);
// Do predictions and compute mean absolute error
outputs.resize(inputs.rows(),cur_fa->getExpectedOutputDim());
cur_fa->predict(inputs,outputs);
meanAbsoluteErrorPerOutputDimension(targets,outputs);
#ifdef NDEBUG
// Here, we time the predict function on single inputs, i.e. typical usage in a
// real-time loop on a robot.
// It's better to test this code with -03 instead of -ggdb. That's why its only run
// when NDEBUG is set.
MatrixXd input = inputs.row(0);
MatrixXd output(input.rows(),input.cols());
int n_calls = 1000000;
clock_t begin = clock();
for (int call=0; call<n_calls; call++)
{
cur_fa->predict(input,output);
input(0,0) += 0.1/n_calls;
}
clock_t end = clock();
double time_sec = (double)(end - begin) / static_cast<double>( CLOCKS_PER_SEC );
cout << " time for " << n_calls << " calls of predict: "<< time_sec;
double time_per_call = time_sec/n_calls;
cout << " => " << (int)(1.0/(time_per_call*1000)) << "kHz" << endl;
#endif
delete cur_fa;
}
}
return 0;
}
<commit_msg>Removed getFunctionApproximatorByName.cpp (replaced by FunctionApproxitorFactory)<commit_after>/**
* \file demoFunctionApproximatorTraining.cpp
* \author Freek Stulp
* \brief Demonstrates how to train all functionapproximators with 1D and 2D data.
*
* \ingroup Demos
* \ingroup FunctionApproximators
*
* This file is part of DmpBbo, a set of libraries and programs for the
* black-box optimization of dynamical movement primitives.
* Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech
*
* DmpBbo 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 of the License, or
* (at your option) any later version.
*
* DmpBbo 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 DmpBbo. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <ctime>
#include <boost/filesystem.hpp>
#include "functionapproximators/FunctionApproximator.hpp"
#include "functionapproximators/MetaParametersLWR.hpp"
#include "functionapproximators/FunctionApproximatorLWR.hpp"
#include "functionapproximators/MetaParametersGMR.hpp"
#include "functionapproximators/FunctionApproximatorGMR.hpp"
#include "functionapproximators/MetaParametersRRRFF.hpp"
#include "functionapproximators/FunctionApproximatorRRRFF.hpp"
#include "functionapproximators/MetaParametersGPR.hpp"
#include "functionapproximators/FunctionApproximatorGPR.hpp"
#include "functionapproximators/MetaParametersRBFN.hpp"
#include "functionapproximators/FunctionApproximatorRBFN.hpp"
#ifdef USE_LWPR
#include "functionapproximators/MetaParametersLWPR.hpp"
#include "functionapproximators/FunctionApproximatorLWPR.hpp"
#endif // USE_LWPR
#include "targetFunction.hpp"
using namespace std;
using namespace Eigen;
using namespace DmpBbo;
FunctionApproximator* getFunctionApproximatorByName(std::string name, int input_dim)
{
FunctionApproximator* fa = NULL;
if (name.compare("LWR")==0)
{
// Locally Weighted Regression
double intersection = 0.6;
Eigen::VectorXi num_rfs_per_dim = Eigen::VectorXi::Constant(input_dim,9);
if (input_dim==2) {
num_rfs_per_dim[0] = 7;
num_rfs_per_dim[1] = 5;
}
double regularization = 0.0;
MetaParametersLWR* meta_params = new MetaParametersLWR(input_dim,num_rfs_per_dim,intersection,regularization);
fa = new FunctionApproximatorLWR(meta_params);
}
else if (name.compare("GMR")==0)
{
// Gaussian Mixture Regression
int number_of_gaussians = 10;
if (input_dim==2) number_of_gaussians = 10;
MetaParametersGMR* meta_params = new MetaParametersGMR(input_dim,number_of_gaussians);
fa = new FunctionApproximatorGMR(meta_params);
}
else if (name.compare("RRRFF")==0)
{
// RRRFF
int number_of_basis_functions=18;
if (input_dim==2) number_of_basis_functions = 100;
double regularization=0.2;
double gamma=5;
MetaParametersRRRFF* meta_params = new MetaParametersRRRFF(input_dim,number_of_basis_functions,regularization,gamma);
fa = new FunctionApproximatorRRRFF(meta_params);
}
else if (name.compare("RBFN")==0)
{
// Radial Basis Function Network
double intersection = 0.7;
int n_rfs = 9;
if (input_dim==2) n_rfs = 5;
Eigen::VectorXi num_rfs_per_dim = Eigen::VectorXi::Constant(input_dim,n_rfs);
double regularization = 0.0;
MetaParametersRBFN* meta_params = new MetaParametersRBFN(input_dim,num_rfs_per_dim,intersection,regularization);
fa = new FunctionApproximatorRBFN(meta_params);
}
else if (name.compare("GPR")==0)
{
// Gaussian Process Regression
double maximum_covariance = 1.1*1.1;
double length = 0.1;
if (input_dim==2)
{
maximum_covariance = 0.1*0.1;
length = 0.2;
}
MetaParametersGPR* meta_params = new MetaParametersGPR(input_dim,maximum_covariance,length);
fa = new FunctionApproximatorGPR(meta_params);
}
else if (name.compare("LWPR")==0)
{
// Locally Weighted Projection Regression
#ifdef USE_LWPR
double w_gen=0.2;
double w_prune=0.8;
bool update_D=true;
double init_alpha=0.1;
double penalty=0.005;
Eigen::VectorXd init_D=Eigen::VectorXd::Constant(input_dim,200);
MetaParametersLWPR* meta_params = new MetaParametersLWPR(input_dim,init_D,w_gen,w_prune,update_D,init_alpha,penalty);
fa = new FunctionApproximatorLWPR(dynamic_cast<MetaParametersLWPR*>(meta_params));
#else
std::cerr << __FILE__ << ":" << __LINE__ << ":";
std::cerr << "Sorry, LWPR is not available. Is it installed? Returning NULL." << std::endl;
return NULL;
#endif // USE_LWPR
}
if (fa==NULL)
{
std::cerr << __FILE__ << ":" << __LINE__ << ":";
std::cerr << "Function approximator with name '" << name << "' is unknown. Returning NULL." << std::endl;
}
return fa;
}
/** Compute mean absolute error for each column of two matrices.
* \param[in] mat1 First matrix of data
* \param[in] mat2 Second matrix of data
* \return Mean absolute error between the matrices (one value for each column)
*/
VectorXd meanAbsoluteErrorPerOutputDimension(const MatrixXd& mat1, const MatrixXd& mat2)
{
MatrixXd abs_error = (mat1.array()-mat2.array()).abs();
VectorXd mean_abs_error_per_output_dim = abs_error.colwise().mean();
cout << fixed << setprecision(5);
cout << " Mean absolute error ";
if (mean_abs_error_per_output_dim.size()>1) cout << " (per dimension)";
cout << ": " << mean_abs_error_per_output_dim.transpose();
cout << " \t(range of target data is " << mat1.colwise().maxCoeff().array()-mat1.colwise().minCoeff().array() << ")" << endl;
return mean_abs_error_per_output_dim;
}
int main(int n_args, char** args)
{
// First argument may be optional directory to write data to
string directory;
if (n_args>1)
directory = string(args[1]);
vector<string> fa_names;
if (n_args>2)
{
for (int aa=2; aa<n_args; aa++)
fa_names.push_back(string(args[aa]));
}
else
{
fa_names.push_back("LWR");
fa_names.push_back("RRRFF");
fa_names.push_back("LWPR");
fa_names.push_back("GMR");
}
for (int n_input_dims=1; n_input_dims<=2; n_input_dims++)
{
// Generate training data
VectorXi n_samples_per_dim = VectorXi::Constant(1,30); // 25
if (n_input_dims==2)
n_samples_per_dim = VectorXi::Constant(2,10); // 2,25
MatrixXd inputs, targets, outputs;
targetFunction(n_samples_per_dim,inputs,targets);
// Add some noise
//targets = targets + 0.1*VectorXd::Random(targets.rows(),targets.cols());
for (unsigned int i_name=0; i_name<fa_names.size(); i_name++)
{
FunctionApproximator* cur_fa = getFunctionApproximatorByName(fa_names[i_name],n_input_dims);
if (cur_fa==NULL)
continue;
string save_directory;
if (!directory.empty())
save_directory = directory+"/"+fa_names[i_name]+"_"+(n_input_dims==1?"1D":"2D");
bool overwrite = true;
cout << "Training " << cur_fa->getName() << " on " << n_input_dims << "D data...\t";
cur_fa->train(inputs,targets,save_directory,overwrite);
// Do predictions and compute mean absolute error
outputs.resize(inputs.rows(),cur_fa->getExpectedOutputDim());
cur_fa->predict(inputs,outputs);
meanAbsoluteErrorPerOutputDimension(targets,outputs);
#ifdef NDEBUG
// Here, we time the predict function on single inputs, i.e. typical usage in a
// real-time loop on a robot.
// It's better to test this code with -03 instead of -ggdb. That's why its only run
// when NDEBUG is set.
MatrixXd input = inputs.row(0);
MatrixXd output(input.rows(),input.cols());
int n_calls = 1000000;
clock_t begin = clock();
for (int call=0; call<n_calls; call++)
{
cur_fa->predict(input,output);
input(0,0) += 0.1/n_calls;
}
clock_t end = clock();
double time_sec = (double)(end - begin) / static_cast<double>( CLOCKS_PER_SEC );
cout << " time for " << n_calls << " calls of predict: "<< time_sec;
double time_per_call = time_sec/n_calls;
cout << " => " << (int)(1.0/(time_per_call*1000)) << "kHz" << endl;
#endif
delete cur_fa;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>
#include <QtTest>
#include <QObject>
#include <AST.h>
#include <ASTVisitor.h>
#include <TranslationUnit.h>
#include <CppDocument.h>
#include <LookupContext.h>
#include <Symbols.h>
#include <Overview.h>
CPLUSPLUS_USE_NAMESPACE
class ClassSymbols: protected ASTVisitor,
public QMap<ClassSpecifierAST *, Class *>
{
public:
ClassSymbols(Control *control)
: ASTVisitor(control)
{ }
void operator()(AST *ast)
{ accept(ast); }
protected:
virtual bool visit(ClassSpecifierAST *ast)
{
Class *classSymbol = ast->class_symbol;
Q_ASSERT(classSymbol != 0);
insert(ast, classSymbol);
return true;
}
};
class tst_Lookup: public QObject
{
Q_OBJECT
private Q_SLOTS:
void base_class_defined_1();
};
void tst_Lookup::base_class_defined_1()
{
Overview overview;
const QByteArray source = "\n"
"class base {};\n"
"class derived: public base {};\n";
Document::Ptr doc = Document::create("base_class_defined_1");
doc->setSource(source);
doc->parse();
doc->check();
QVERIFY(doc->diagnosticMessages().isEmpty());
QCOMPARE(doc->globalSymbolCount(), 2U);
Snapshot snapshot;
snapshot.insert(doc->fileName(), doc);
Document::Ptr emptyDoc = Document::create("empty");
Class *baseClass = doc->globalSymbolAt(0)->asClass();
QVERIFY(baseClass);
Class *derivedClass = doc->globalSymbolAt(1)->asClass();
QVERIFY(derivedClass);
LookupContext ctx(derivedClass, emptyDoc, doc, snapshot);
const QList<Symbol *> candidates =
ctx.resolveClass(derivedClass->baseClassAt(0)->name());
QCOMPARE(candidates.size(), 1);
QCOMPARE(candidates.at(0), baseClass);
TranslationUnit *unit = doc->translationUnit();
QVERIFY(unit != 0);
TranslationUnitAST *ast = unit->ast()->asTranslationUnit();
QVERIFY(ast != 0);
ClassSymbols classSymbols(doc->control());
classSymbols(ast);
QCOMPARE(classSymbols.size(), 2);
}
QTEST_APPLESS_MAIN(tst_Lookup)
#include "tst_lookup.moc"
<commit_msg>More testing.<commit_after>
#include <QtTest>
#include <QObject>
#include <AST.h>
#include <ASTVisitor.h>
#include <TranslationUnit.h>
#include <CppDocument.h>
#include <LookupContext.h>
#include <Symbols.h>
#include <Overview.h>
CPLUSPLUS_USE_NAMESPACE
template <template <typename, typename> class _Map, typename _T1, typename _T2>
_Map<_T2, _T1> invert(const _Map<_T1, _T2> &m)
{
_Map<_T2, _T1> i;
typename _Map<_T1, _T2>::const_iterator it = m.constBegin();
for (; it != m.constEnd(); ++it) {
i.insertMulti(it.value(), it.key());
}
return i;
}
class ClassSymbols: protected ASTVisitor,
public QMap<ClassSpecifierAST *, Class *>
{
public:
ClassSymbols(Control *control)
: ASTVisitor(control)
{ }
QMap<ClassSpecifierAST *, Class *> asMap() const
{ return *this; }
void operator()(AST *ast)
{ accept(ast); }
protected:
virtual bool visit(ClassSpecifierAST *ast)
{
Class *classSymbol = ast->class_symbol;
Q_ASSERT(classSymbol != 0);
insert(ast, classSymbol);
return true;
}
};
class tst_Lookup: public QObject
{
Q_OBJECT
private Q_SLOTS:
void base_class_defined_1();
};
void tst_Lookup::base_class_defined_1()
{
Overview overview;
const QByteArray source = "\n"
"class base {};\n"
"class derived: public base {};\n";
Document::Ptr doc = Document::create("base_class_defined_1");
doc->setSource(source);
doc->parse();
doc->check();
QVERIFY(doc->diagnosticMessages().isEmpty());
QCOMPARE(doc->globalSymbolCount(), 2U);
Snapshot snapshot;
snapshot.insert(doc->fileName(), doc);
Document::Ptr emptyDoc = Document::create("<empty>");
Class *baseClass = doc->globalSymbolAt(0)->asClass();
QVERIFY(baseClass);
Class *derivedClass = doc->globalSymbolAt(1)->asClass();
QVERIFY(derivedClass);
LookupContext ctx(derivedClass, emptyDoc, doc, snapshot);
const QList<Symbol *> candidates =
ctx.resolveClass(derivedClass->baseClassAt(0)->name());
QCOMPARE(candidates.size(), 1);
QCOMPARE(candidates.at(0), baseClass);
TranslationUnit *unit = doc->translationUnit();
QVERIFY(unit != 0);
TranslationUnitAST *ast = unit->ast()->asTranslationUnit();
QVERIFY(ast != 0);
ClassSymbols classSymbols(doc->control());
classSymbols(ast);
QCOMPARE(classSymbols.size(), 2);
const QMap<Class *, ClassSpecifierAST *> classToAST =
invert(classSymbols.asMap());
QVERIFY(classToAST.value(baseClass) != 0);
QVERIFY(classToAST.value(derivedClass) != 0);
}
QTEST_APPLESS_MAIN(tst_Lookup)
#include "tst_lookup.moc"
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qdeviceinfo.h"
QT_USE_NAMESPACE
class tst_QDeviceInfo : public QObject
{
Q_OBJECT
private slots:
void tst_imei();
void tst_lockTypes();
};
void tst_QDeviceInfo::tst_imei()
{
QDeviceInfo deviceInfo;
int imeiCount = deviceInfo.imeiCount();
QVERIFY(imeiCount >= -1);
QVERIFY(deviceInfo.imei(-1).isEmpty());
QVERIFY(deviceInfo.imei(imeiCount).isEmpty());
QRegExp imeiPattern("(\\d{0,0}|\\d{15,15})");
for (int i = 0; i < imeiCount; ++i)
QVERIFY(imeiPattern.exactMatch(deviceInfo.imei(i)));
}
void tst_QDeviceInfo::tst_lockTypes()
{
QDeviceInfo deviceInfo;
QDeviceInfo::LockTypeFlags enabledLocks = deviceInfo.enabledLocks();
QDeviceInfo::LockTypeFlags activeLocks = deviceInfo.activatedLocks();
QVERIFY((activeLocks & enabledLocks) == activeLocks);
QVERIFY((activeLocks | enabledLocks) == enabledLocks);
}
QTEST_MAIN(tst_QDeviceInfo)
#include "tst_qdeviceinfo.moc"
<commit_msg>added unittests<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtSystems module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qdeviceinfo.h"
QT_USE_NAMESPACE
class tst_QDeviceInfo : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void tst_imei();
void tst_lockTypes();
void tst_version();
void tst_manufacturer();
void tst_model();
void tst_productName();
void tst_uniqueDeviceID();
void tst_hasFeature();
void tst_thermalState();
private:
QDeviceInfo *deviceInfo;
};
void tst_QDeviceInfo::initTestCase()
{
deviceInfo = new QDeviceInfo();
}
void tst_QDeviceInfo::cleanupTestCase()
{
delete deviceInfo;
}
void tst_QDeviceInfo::tst_imei()
{
int imeiCount = deviceInfo->imeiCount();
QVERIFY(imeiCount >= -1);
QVERIFY(deviceInfo->imei(-1).isEmpty());
QVERIFY(deviceInfo->imei(imeiCount).isEmpty());
QRegExp imeiPattern("(\\d{0,0}|\\d{15,15})");
for (int i = 0; i < imeiCount; ++i)
QVERIFY(imeiPattern.exactMatch(deviceInfo->imei(i)));
}
void tst_QDeviceInfo::tst_lockTypes()
{
QDeviceInfo::LockTypeFlags enabledLocks = deviceInfo->enabledLocks();
QDeviceInfo::LockTypeFlags activeLocks = deviceInfo->activatedLocks();
QVERIFY((activeLocks & enabledLocks) == activeLocks);
QVERIFY((activeLocks | enabledLocks) == enabledLocks);
}
void tst_QDeviceInfo::tst_version()
{
QRegExp osversion(QString::fromAscii("(\\d+(\\.\\d+)*)?"));
QVERIFY(osversion.exactMatch(deviceInfo->version(QDeviceInfo::Os)));
QRegExp firmwareversion(QString::fromAscii(".*"));
QVERIFY(firmwareversion.exactMatch(deviceInfo->version(QDeviceInfo::Firmware)));
}
void tst_QDeviceInfo::tst_manufacturer()
{
QRegExp manufacturer(".*");
QVERIFY(manufacturer.exactMatch(deviceInfo->manufacturer()));
}
void tst_QDeviceInfo::tst_model()
{
QRegExp model(".*");
QVERIFY(model.exactMatch(deviceInfo->model()));
}
void tst_QDeviceInfo::tst_productName()
{
QRegExp productName(".*");
QVERIFY(productName.exactMatch(deviceInfo->productName()));
}
void tst_QDeviceInfo::tst_uniqueDeviceID()
{
QRegExp uniqueId("\\d*");
QVERIFY(uniqueId.exactMatch(deviceInfo->uniqueDeviceID()));
}
void tst_QDeviceInfo::tst_hasFeature()
{
QList<QDeviceInfo::Feature> featureList;
featureList << QDeviceInfo::Bluetooth
<< QDeviceInfo::Camera
<< QDeviceInfo::FmRadio
<< QDeviceInfo::FmTransmitter
<< QDeviceInfo::Haptics
<< QDeviceInfo::Infrared
<< QDeviceInfo::Led
<< QDeviceInfo::MemoryCard
<< QDeviceInfo::Positioning
<< QDeviceInfo::Sim
<< QDeviceInfo::Usb
<< QDeviceInfo::Vibration
<< QDeviceInfo::VideoOut
<< QDeviceInfo::Wlan;
foreach (QDeviceInfo::Feature feature, featureList) {
bool isPresent = deviceInfo->hasFeature(feature);
QVERIFY(isPresent == true || isPresent == false);
}
}
void tst_QDeviceInfo::tst_thermalState()
{
QDeviceInfo::ThermalState state = deviceInfo->thermalState();
QVERIFY(state == QDeviceInfo::UnknownThermal ||
state == QDeviceInfo::NormalThermal ||
state == QDeviceInfo::WarningThermal ||
state == QDeviceInfo::AlertThermal ||
state == QDeviceInfo::ErrorThermal);
}
QTEST_MAIN(tst_QDeviceInfo)
#include "tst_qdeviceinfo.moc"
<|endoftext|>
|
<commit_before>/**
* The MIT License (MIT)
*
* Copyright © 2019 Ruben Van Boxem
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**/
#include <css/ostream.h++>
#include <css/grammar/radial_gradient.h++>
#include "css/test_rule.h++"
#include <boost/fusion/adapted/std_pair.hpp>
#include <utility>
namespace
{
const auto circle_default = "circle";
const auto circle_radius = "circle 5 pt";
const auto circle_extent = "circle closest-corner";
const auto ellipse_default = "ellipse";
const auto ellipse_radii = "ellipse 3cm 5rem";
const auto ellipse_extent = "ellipse farthest-side";
const auto non_repeating_radial_gradient = "radial-gradient(ellipse at top, red, blue)";
const auto repeating_radial_gradient = "repeating-radial-gradient(at top right, yellow 30%, green 100vw, black)";
const auto default_shape_position_radial_gradient = "radial-gradient(#FF00FF, rgb(255,0,0))";
const auto leading_comma = "radial-gradient(, red)";
const auto missing_comma = "radial-gradient(at top red)";
}
int main()
{
using skui::test::check_rule_failure;
using skui::test::check_rule_success;
using skui::css::grammar::circle;
check_rule_success(circle, circle_default,
skui::css::radial_gradient::circle{skui::css::radial_gradient::extent::farthest_corner});
check_rule_success(circle, circle_radius,
skui::css::radial_gradient::circle{skui::css::length{5, skui::css::unit::pt}});
check_rule_success(circle, circle_extent,
skui::css::radial_gradient::circle{skui::css::radial_gradient::extent::closest_corner});
using skui::css::grammar::ellipse;
check_rule_success(ellipse, ellipse_default,
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_corner});
check_rule_success(ellipse, ellipse_radii,
skui::css::radial_gradient::ellipse{skui::graphics::size2D<skui::css::length>{{3, skui::css::unit::cm},
{5, skui::css::unit::rem}}});
check_rule_success(ellipse, ellipse_extent,
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_side});
using skui::css::grammar::radial_gradient;
check_rule_success(radial_gradient, non_repeating_radial_gradient,
skui::css::radial_gradient{{false,
{{skui::css::colors::red, {}},
{skui::css::colors::blue, {}}}},
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_corner},
skui::css::top});
check_rule_success(radial_gradient, repeating_radial_gradient,
skui::css::radial_gradient{{true,
{{skui::css::colors::yellow, {{30, skui::css::unit::percentage}}},
{skui::css::colors::green, {{100, skui::css::unit::vw}}},
{skui::css::colors::black, {}}}},
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_corner},
skui::css::top_right});
check_rule_success(radial_gradient, default_shape_position_radial_gradient,
skui::css::radial_gradient{{false,
{{skui::css::colors::magenta, {}},
{skui::css::colors::red, {}}}},
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_corner},
skui::css::center});
check_rule_failure(radial_gradient, leading_comma);
check_rule_failure(radial_gradient, missing_comma);
return skui::test::exit_code;
}
<commit_msg>Remove unused include.<commit_after>/**
* The MIT License (MIT)
*
* Copyright © 2019 Ruben Van Boxem
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**/
#include <css/ostream.h++>
#include <css/grammar/radial_gradient.h++>
#include "css/test_rule.h++"
#include <utility>
namespace
{
const auto circle_default = "circle";
const auto circle_radius = "circle 5 pt";
const auto circle_extent = "circle closest-corner";
const auto ellipse_default = "ellipse";
const auto ellipse_radii = "ellipse 3cm 5rem";
const auto ellipse_extent = "ellipse farthest-side";
const auto non_repeating_radial_gradient = "radial-gradient(ellipse at top, red, blue)";
const auto repeating_radial_gradient = "repeating-radial-gradient(at top right, yellow 30%, green 100vw, black)";
const auto default_shape_position_radial_gradient = "radial-gradient(#FF00FF, rgb(255,0,0))";
const auto leading_comma = "radial-gradient(, red)";
const auto missing_comma = "radial-gradient(at top red)";
}
int main()
{
using skui::test::check_rule_failure;
using skui::test::check_rule_success;
using skui::css::grammar::circle;
check_rule_success(circle, circle_default,
skui::css::radial_gradient::circle{skui::css::radial_gradient::extent::farthest_corner});
check_rule_success(circle, circle_radius,
skui::css::radial_gradient::circle{skui::css::length{5, skui::css::unit::pt}});
check_rule_success(circle, circle_extent,
skui::css::radial_gradient::circle{skui::css::radial_gradient::extent::closest_corner});
using skui::css::grammar::ellipse;
check_rule_success(ellipse, ellipse_default,
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_corner});
check_rule_success(ellipse, ellipse_radii,
skui::css::radial_gradient::ellipse{skui::graphics::size2D<skui::css::length>{{3, skui::css::unit::cm},
{5, skui::css::unit::rem}}});
check_rule_success(ellipse, ellipse_extent,
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_side});
using skui::css::grammar::radial_gradient;
check_rule_success(radial_gradient, non_repeating_radial_gradient,
skui::css::radial_gradient{{false,
{{skui::css::colors::red, {}},
{skui::css::colors::blue, {}}}},
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_corner},
skui::css::top});
check_rule_success(radial_gradient, repeating_radial_gradient,
skui::css::radial_gradient{{true,
{{skui::css::colors::yellow, {{30, skui::css::unit::percentage}}},
{skui::css::colors::green, {{100, skui::css::unit::vw}}},
{skui::css::colors::black, {}}}},
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_corner},
skui::css::top_right});
check_rule_success(radial_gradient, default_shape_position_radial_gradient,
skui::css::radial_gradient{{false,
{{skui::css::colors::magenta, {}},
{skui::css::colors::red, {}}}},
skui::css::radial_gradient::ellipse{skui::css::radial_gradient::extent::farthest_corner},
skui::css::center});
check_rule_failure(radial_gradient, leading_comma);
check_rule_failure(radial_gradient, missing_comma);
return skui::test::exit_code;
}
<|endoftext|>
|
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "llvm/ADT/STLExtras.h"
#include "mlir/IR/SymbolTable.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassRegistry.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "mlir/Transforms/Utils.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace TF {
namespace {
// Clones FuncOp's until they have a single use only (or no users).
//
// The tf-shape-inference pass doesn't support functions that have more than
// a single use. But some real code from frontends does end up creating code
// like that. For example, the same LSTM cell function or loop body function
// will be reused.
//
// This pass clones functions as needed to establish the invariant that all
// functions have a single use. This can in principle cause exponential code
// size bloat, and should in general be guided by a proper cost model.
//
// There are two factors which should be considered by a principled replacement
// to this pass:
//
// 1. TF currently relies on "sufficiently good shape inference" for
// correctness so for now the cost of doing this seems acceptable since
// pathological cases haven't hit us yet.
//
// 2. Cloning functions can help by allowing code to be specialized (much as
// inlining does). In fact, tf-shape-inference attempts to do specialization
// of callees which is difficult if callees have multiple uses.
class GuaranteeAllFuncsOneUse
: public PassWrapper<GuaranteeAllFuncsOneUse, OperationPass<ModuleOp>> {
public:
void runOnOperation() override {
if (failed(Run())) {
signalPassFailure();
}
}
LogicalResult Run() {
auto module = getOperation();
// Overall strategy:
// Fixed point iteration, iteratively applying a rule that clones
// any FuncOp with more than one use to eliminate its uses.
SymbolTableCollection symbol_table_collection;
SymbolTable &symbol_table = symbol_table_collection.getSymbolTable(module);
bool made_changes = false;
// This value needs to be low enough to actually stop compilation in a
// reasonable time, but not too low that it blocks real programs.
// This number was chosen semi-randomly.
const int k_max_clones = 1000;
int num_clones = 0;
do {
SymbolUserMap symbol_users(symbol_table_collection, module);
made_changes = false;
for (auto func : llvm::make_early_inc_range(module.getOps<FuncOp>())) {
ArrayRef<Operation *> users = symbol_users.getUsers(func);
if (users.size() <= 1) {
continue;
}
// At this point, we know we are going to change the module.
made_changes = true;
for (Operation *user : users.drop_front()) {
if (num_clones++ > k_max_clones) {
return func.emitError()
<< "reached cloning limit (likely recursive call graph or "
"repeated diamond-like call structure "
"or just very large program)";
}
FuncOp new_func = func.clone();
symbol_table.insert(new_func);
new_func.setPrivate();
if (failed(SymbolTable::replaceAllSymbolUses(func, new_func.getName(),
user))) {
return func.emitError() << "could not replace symbol use";
}
}
}
} while (made_changes);
return success();
}
};
} // namespace
std::unique_ptr<OperationPass<ModuleOp>> CreateGuaranteeAllFuncsOneUsePass() {
return std::make_unique<GuaranteeAllFuncsOneUse>();
}
static PassRegistration<GuaranteeAllFuncsOneUse> pass(
"tf-guarantee-all-funcs-one-use",
"Guarantee all FuncOp's have only a single use.");
} // namespace TF
} // namespace mlir
<commit_msg>Bump kMaxClones limit up<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "llvm/ADT/STLExtras.h"
#include "mlir/IR/SymbolTable.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Pass/PassRegistry.h" // from @llvm-project
#include "mlir/Support/LLVM.h" // from @llvm-project
#include "mlir/Support/LogicalResult.h" // from @llvm-project
#include "mlir/Transforms/Utils.h" // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h"
namespace mlir {
namespace TF {
namespace {
// Clones FuncOp's until they have a single use only (or no users).
//
// The tf-shape-inference pass doesn't support functions that have more than
// a single use. But some real code from frontends does end up creating code
// like that. For example, the same LSTM cell function or loop body function
// will be reused.
//
// This pass clones functions as needed to establish the invariant that all
// functions have a single use. This can in principle cause exponential code
// size bloat, and should in general be guided by a proper cost model.
//
// There are two factors which should be considered by a principled replacement
// to this pass:
//
// 1. TF currently relies on "sufficiently good shape inference" for
// correctness so for now the cost of doing this seems acceptable since
// pathological cases haven't hit us yet.
//
// 2. Cloning functions can help by allowing code to be specialized (much as
// inlining does). In fact, tf-shape-inference attempts to do specialization
// of callees which is difficult if callees have multiple uses.
class GuaranteeAllFuncsOneUse
: public PassWrapper<GuaranteeAllFuncsOneUse, OperationPass<ModuleOp>> {
public:
void runOnOperation() override {
if (failed(Run())) {
signalPassFailure();
}
}
LogicalResult Run() {
auto module = getOperation();
// Overall strategy:
// Fixed point iteration, iteratively applying a rule that clones
// any FuncOp with more than one use to eliminate its uses.
SymbolTableCollection symbol_table_collection;
SymbolTable &symbol_table = symbol_table_collection.getSymbolTable(module);
bool made_changes = false;
// This value needs to be low enough to actually stop compilation in a
// reasonable time, but not too low that it blocks real programs.
// This number was chosen semi-randomly.
// TODO(jpienaar): Switch to a more context aware heuristic.
const int kMaxClones = 10000;
int num_clones = 0;
do {
SymbolUserMap symbol_users(symbol_table_collection, module);
made_changes = false;
for (auto func : llvm::make_early_inc_range(module.getOps<FuncOp>())) {
ArrayRef<Operation *> users = symbol_users.getUsers(func);
if (users.size() <= 1) {
continue;
}
// At this point, we know we are going to change the module.
made_changes = true;
for (Operation *user : users.drop_front()) {
if (num_clones++ > kMaxClones) {
return func.emitError()
<< "reached cloning limit (likely recursive call graph or "
"repeated diamond-like call structure "
"or just very large program)";
}
FuncOp new_func = func.clone();
symbol_table.insert(new_func);
new_func.setPrivate();
if (failed(SymbolTable::replaceAllSymbolUses(func, new_func.getName(),
user))) {
return func.emitError() << "could not replace symbol use";
}
}
}
} while (made_changes);
return success();
}
};
} // namespace
std::unique_ptr<OperationPass<ModuleOp>> CreateGuaranteeAllFuncsOneUsePass() {
return std::make_unique<GuaranteeAllFuncsOneUse>();
}
static PassRegistration<GuaranteeAllFuncsOneUse> pass(
"tf-guarantee-all-funcs-one-use",
"Guarantee all FuncOp's have only a single use.");
} // namespace TF
} // namespace mlir
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <vector>
// template <class InputIter> vector(InputIter first, InputIter last);
#include <vector>
#include <cassert>
#include <cstddef>
#include "test_macros.h"
#include "test_iterators.h"
#include "test_allocator.h"
#include "min_allocator.h"
#include "asan_testing.h"
#if TEST_STD_VER >= 11
#include "emplace_constructible.h"
#include "container_test_types.h"
#endif
template <class C, class Iterator>
void test(Iterator first, Iterator last) {
C c(first, last);
LIBCPP_ASSERT(c.__invariants());
assert(c.size() == static_cast<std::size_t>(std::distance(first, last)));
LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
for (typename C::const_iterator i = c.cbegin(), e = c.cend(); i != e;
++i, ++first)
assert(*i == *first);
}
static void basic_test_cases() {
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 1, 0};
int* an = a + sizeof(a) / sizeof(a[0]);
test<std::vector<int> >(input_iterator<const int*>(a),
input_iterator<const int*>(an));
test<std::vector<int> >(forward_iterator<const int*>(a),
forward_iterator<const int*>(an));
test<std::vector<int> >(bidirectional_iterator<const int*>(a),
bidirectional_iterator<const int*>(an));
test<std::vector<int> >(random_access_iterator<const int*>(a),
random_access_iterator<const int*>(an));
test<std::vector<int> >(a, an);
test<std::vector<int, limited_allocator<int, 63> > >(
input_iterator<const int*>(a), input_iterator<const int*>(an));
// Add 1 for implementations that dynamically allocate a container proxy.
test<std::vector<int, limited_allocator<int, 18 + 1> > >(
forward_iterator<const int*>(a), forward_iterator<const int*>(an));
test<std::vector<int, limited_allocator<int, 18 + 1> > >(
bidirectional_iterator<const int*>(a),
bidirectional_iterator<const int*>(an));
test<std::vector<int, limited_allocator<int, 18 + 1> > >(
random_access_iterator<const int*>(a),
random_access_iterator<const int*>(an));
test<std::vector<int, limited_allocator<int, 18 + 1> > >(a, an);
#if TEST_STD_VER >= 11
test<std::vector<int, min_allocator<int> > >(input_iterator<const int*>(a),
input_iterator<const int*>(an));
test<std::vector<int, min_allocator<int> > >(
forward_iterator<const int*>(a), forward_iterator<const int*>(an));
test<std::vector<int, min_allocator<int> > >(
bidirectional_iterator<const int*>(a),
bidirectional_iterator<const int*>(an));
test<std::vector<int, min_allocator<int> > >(
random_access_iterator<const int*>(a),
random_access_iterator<const int*>(an));
test<std::vector<int> >(a, an);
#endif
}
void emplaceable_concept_tests() {
#if TEST_STD_VER >= 11
int arr1[] = {42};
int arr2[] = {1, 101, 42};
{
using T = EmplaceConstructible<int>;
using It = forward_iterator<int*>;
{
std::vector<T> v(It(arr1), It(std::end(arr1)));
assert(v[0].value == 42);
}
{
std::vector<T> v(It(arr2), It(std::end(arr2)));
assert(v[0].value == 1);
assert(v[1].value == 101);
assert(v[2].value == 42);
}
}
{
using T = EmplaceConstructibleAndMoveInsertable<int>;
using It = input_iterator<int*>;
{
std::vector<T> v(It(arr1), It(std::end(arr1)));
assert(v[0].copied == 0);
assert(v[0].value == 42);
}
{
std::vector<T> v(It(arr2), It(std::end(arr2)));
//assert(v[0].copied == 0);
assert(v[0].value == 1);
//assert(v[1].copied == 0);
assert(v[1].value == 101);
assert(v[2].copied == 0);
assert(v[2].value == 42);
}
}
#endif
}
void test_ctor_under_alloc() {
#if TEST_STD_VER >= 11
int arr1[] = {42};
int arr2[] = {1, 101, 42};
{
using C = TCT::vector<>;
using It = forward_iterator<int*>;
{
ExpectConstructGuard<int&> G(1);
C v(It(arr1), It(std::end(arr1)));
}
{
ExpectConstructGuard<int&> G(3);
C v(It(arr2), It(std::end(arr2)));
}
}
{
using C = TCT::vector<>;
using It = input_iterator<int*>;
{
ExpectConstructGuard<int&> G(1);
C v(It(arr1), It(std::end(arr1)));
}
{
//ExpectConstructGuard<int&> G(3);
//C v(It(arr2), It(std::end(arr2)), a);
}
}
#endif
}
// Initialize a vector with a different value type.
void test_ctor_with_different_value_type() {
{
// Make sure initialization is performed with each element value, not with
// a memory blob.
float array[3] = {0.0f, 1.0f, 2.0f};
std::vector<int> v(array, array + 3);
assert(v[0] == 0);
assert(v[1] == 1);
assert(v[2] == 2);
}
struct X { int x; };
struct Y { int y; };
struct Z : X, Y { int z; };
{
Z z;
Z *array[1] = { &z };
// Though the types Z* and Y* are very similar, initialization still cannot
// be done with `memcpy`.
std::vector<Y*> v(array, array + 1);
assert(v[0] == &z);
}
{
// Though the types are different, initialization can be done with `memcpy`.
int32_t array[1] = { -1 };
std::vector<uint32_t> v(array, array + 1);
assert(v[0] == 4294967295);
}
}
int main(int, char**) {
basic_test_cases();
emplaceable_concept_tests(); // See PR34898
test_ctor_under_alloc();
test_ctor_with_different_value_type();
return 0;
}
<commit_msg>Fix a vector test to not use a local type as a template parameter. This causes a warning on C++03. NFC<commit_after>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <vector>
// template <class InputIter> vector(InputIter first, InputIter last);
#include <vector>
#include <cassert>
#include <cstddef>
#include "test_macros.h"
#include "test_iterators.h"
#include "test_allocator.h"
#include "min_allocator.h"
#include "asan_testing.h"
#if TEST_STD_VER >= 11
#include "emplace_constructible.h"
#include "container_test_types.h"
#endif
template <class C, class Iterator>
void test(Iterator first, Iterator last) {
C c(first, last);
LIBCPP_ASSERT(c.__invariants());
assert(c.size() == static_cast<std::size_t>(std::distance(first, last)));
LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
for (typename C::const_iterator i = c.cbegin(), e = c.cend(); i != e;
++i, ++first)
assert(*i == *first);
}
static void basic_test_cases() {
int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4, 3, 1, 0};
int* an = a + sizeof(a) / sizeof(a[0]);
test<std::vector<int> >(input_iterator<const int*>(a),
input_iterator<const int*>(an));
test<std::vector<int> >(forward_iterator<const int*>(a),
forward_iterator<const int*>(an));
test<std::vector<int> >(bidirectional_iterator<const int*>(a),
bidirectional_iterator<const int*>(an));
test<std::vector<int> >(random_access_iterator<const int*>(a),
random_access_iterator<const int*>(an));
test<std::vector<int> >(a, an);
test<std::vector<int, limited_allocator<int, 63> > >(
input_iterator<const int*>(a), input_iterator<const int*>(an));
// Add 1 for implementations that dynamically allocate a container proxy.
test<std::vector<int, limited_allocator<int, 18 + 1> > >(
forward_iterator<const int*>(a), forward_iterator<const int*>(an));
test<std::vector<int, limited_allocator<int, 18 + 1> > >(
bidirectional_iterator<const int*>(a),
bidirectional_iterator<const int*>(an));
test<std::vector<int, limited_allocator<int, 18 + 1> > >(
random_access_iterator<const int*>(a),
random_access_iterator<const int*>(an));
test<std::vector<int, limited_allocator<int, 18 + 1> > >(a, an);
#if TEST_STD_VER >= 11
test<std::vector<int, min_allocator<int> > >(input_iterator<const int*>(a),
input_iterator<const int*>(an));
test<std::vector<int, min_allocator<int> > >(
forward_iterator<const int*>(a), forward_iterator<const int*>(an));
test<std::vector<int, min_allocator<int> > >(
bidirectional_iterator<const int*>(a),
bidirectional_iterator<const int*>(an));
test<std::vector<int, min_allocator<int> > >(
random_access_iterator<const int*>(a),
random_access_iterator<const int*>(an));
test<std::vector<int> >(a, an);
#endif
}
void emplaceable_concept_tests() {
#if TEST_STD_VER >= 11
int arr1[] = {42};
int arr2[] = {1, 101, 42};
{
using T = EmplaceConstructible<int>;
using It = forward_iterator<int*>;
{
std::vector<T> v(It(arr1), It(std::end(arr1)));
assert(v[0].value == 42);
}
{
std::vector<T> v(It(arr2), It(std::end(arr2)));
assert(v[0].value == 1);
assert(v[1].value == 101);
assert(v[2].value == 42);
}
}
{
using T = EmplaceConstructibleAndMoveInsertable<int>;
using It = input_iterator<int*>;
{
std::vector<T> v(It(arr1), It(std::end(arr1)));
assert(v[0].copied == 0);
assert(v[0].value == 42);
}
{
std::vector<T> v(It(arr2), It(std::end(arr2)));
//assert(v[0].copied == 0);
assert(v[0].value == 1);
//assert(v[1].copied == 0);
assert(v[1].value == 101);
assert(v[2].copied == 0);
assert(v[2].value == 42);
}
}
#endif
}
void test_ctor_under_alloc() {
#if TEST_STD_VER >= 11
int arr1[] = {42};
int arr2[] = {1, 101, 42};
{
using C = TCT::vector<>;
using It = forward_iterator<int*>;
{
ExpectConstructGuard<int&> G(1);
C v(It(arr1), It(std::end(arr1)));
}
{
ExpectConstructGuard<int&> G(3);
C v(It(arr2), It(std::end(arr2)));
}
}
{
using C = TCT::vector<>;
using It = input_iterator<int*>;
{
ExpectConstructGuard<int&> G(1);
C v(It(arr1), It(std::end(arr1)));
}
{
//ExpectConstructGuard<int&> G(3);
//C v(It(arr2), It(std::end(arr2)), a);
}
}
#endif
}
// In C++03, you can't instantiate a template with a local type.
struct B1 { int x; };
struct B2 { int y; };
struct Der : B1, B2 { int z; };
// Initialize a vector with a different value type.
void test_ctor_with_different_value_type() {
{
// Make sure initialization is performed with each element value, not with
// a memory blob.
float array[3] = {0.0f, 1.0f, 2.0f};
std::vector<int> v(array, array + 3);
assert(v[0] == 0);
assert(v[1] == 1);
assert(v[2] == 2);
}
{
Der z;
Der *array[1] = { &z };
// Though the types Der* and B2* are very similar, initialization still cannot
// be done with `memcpy`.
std::vector<B2*> v(array, array + 1);
assert(v[0] == &z);
}
{
// Though the types are different, initialization can be done with `memcpy`.
int32_t array[1] = { -1 };
std::vector<uint32_t> v(array, array + 1);
assert(v[0] == 4294967295);
}
}
int main(int, char**) {
basic_test_cases();
emplaceable_concept_tests(); // See PR34898
test_ctor_under_alloc();
test_ctor_with_different_value_type();
return 0;
}
<|endoftext|>
|
<commit_before>// RUN: %clang_cc1 %s -emit-llvm -O1 -o - -triple=i686-apple-darwin9 -std=c++11 | FileCheck %s
// CHECK-DAG: @PR22043 = local_unnamed_addr global i32 0, align 4
typedef _Atomic(int) AtomicInt;
AtomicInt PR22043 = AtomicInt();
// CHECK-DAG: @_ZN7PR180978constant1aE = local_unnamed_addr global { i16, i8 } { i16 1, i8 6 }, align 4
// CHECK-DAG: @_ZN7PR180978constant1bE = local_unnamed_addr global { i16, i8 } { i16 2, i8 6 }, align 4
// CHECK-DAG: @_ZN7PR180978constant1cE = local_unnamed_addr global { i16, i8 } { i16 3, i8 6 }, align 4
// CHECK-DAG: @_ZN7PR180978constant1yE = local_unnamed_addr global { { i16, i8 }, i32 } { { i16, i8 } { i16 4, i8 6 }, i32 5 }, align 4
struct A {
_Atomic(int) i;
A(int j);
void v(int j);
};
// Storing to atomic values should be atomic
// CHECK: store atomic i32
void A::v(int j) { i = j; }
// Initialising atomic values should not be atomic
// CHECK-NOT: store atomic
A::A(int j) : i(j) {}
struct B {
int i;
B(int x) : i(x) {}
};
_Atomic(B) b;
// CHECK-LABEL: define void @_Z11atomic_initR1Ai
void atomic_init(A& a, int i) {
// CHECK-NOT: atomic
// CHECK: tail call void @_ZN1BC1Ei
__c11_atomic_init(&b, B(i));
// CHECK-NEXT: ret void
}
// CHECK-LABEL: define void @_Z16atomic_init_boolPU7_Atomicbb
void atomic_init_bool(_Atomic(bool) *ab, bool b) {
// CHECK-NOT: atomic
// CHECK: {{zext i1.*to i8}}
// CHECK-NEXT: store i8
__c11_atomic_init(ab, b);
// CHECK-NEXT: ret void
}
struct AtomicBoolMember {
_Atomic(bool) ab;
AtomicBoolMember(bool b);
};
// CHECK-LABEL: define void @_ZN16AtomicBoolMemberC2Eb
// CHECK: {{zext i1.*to i8}}
// CHECK-NEXT: store i8
// CHECK-NEXT: ret void
AtomicBoolMember::AtomicBoolMember(bool b) : ab(b) { }
namespace PR18097 {
namespace dynamic {
struct X {
X(int);
short n;
char c;
};
// CHECK-LABEL: define {{.*}} @__cxx_global_var_init
// CHECK: call void @_ZN7PR180977dynamic1XC1Ei({{.*}}* nonnull @_ZN7PR180977dynamic1aE, i32 1)
_Atomic(X) a = X(1);
// CHECK-LABEL: define {{.*}} @__cxx_global_var_init
// CHECK: call void @_ZN7PR180977dynamic1XC1Ei({{.*}}* nonnull @_ZN7PR180977dynamic1bE, i32 2)
_Atomic(X) b(X(2));
// CHECK-LABEL: define {{.*}} @__cxx_global_var_init
// CHECK: call void @_ZN7PR180977dynamic1XC1Ei({{.*}}* nonnull @_ZN7PR180977dynamic1cE, i32 3)
_Atomic(X) c{X(3)};
struct Y {
_Atomic(X) a;
_Atomic(int) b;
};
// CHECK-LABEL: define {{.*}} @__cxx_global_var_init
// CHECK: call void @_ZN7PR180977dynamic1XC1Ei({{.*}}* getelementptr inbounds ({{.*}}, {{.*}}* @_ZN7PR180977dynamic1yE, i32 0, i32 0), i32 4)
// CHECK: store i32 5, i32* getelementptr inbounds ({{.*}}, {{.*}}* @_ZN7PR180977dynamic1yE, i32 0, i32 1)
Y y = { X(4), 5 };
}
// CHECKs at top of file.
namespace constant {
struct X {
constexpr X(int n) : n(n) {}
short n;
char c = 6;
};
_Atomic(X) a = X(1);
_Atomic(X) b(X(2));
_Atomic(X) c{X(3)};
struct Y {
_Atomic(X) a;
_Atomic(int) b;
};
Y y = { X(4), 5 };
}
}
<commit_msg>Update test to account for r276604<commit_after>// RUN: %clang_cc1 %s -emit-llvm -O1 -o - -triple=i686-apple-darwin9 -std=c++11 | FileCheck %s
// CHECK-DAG: @PR22043 = local_unnamed_addr global i32 0, align 4
typedef _Atomic(int) AtomicInt;
AtomicInt PR22043 = AtomicInt();
// CHECK-DAG: @_ZN7PR180978constant1aE = local_unnamed_addr global { i16, i8 } { i16 1, i8 6 }, align 4
// CHECK-DAG: @_ZN7PR180978constant1bE = local_unnamed_addr global { i16, i8 } { i16 2, i8 6 }, align 4
// CHECK-DAG: @_ZN7PR180978constant1cE = local_unnamed_addr global { i16, i8 } { i16 3, i8 6 }, align 4
// CHECK-DAG: @_ZN7PR180978constant1yE = local_unnamed_addr global { { i16, i8 }, i32 } { { i16, i8 } { i16 4, i8 6 }, i32 5 }, align 4
struct A {
_Atomic(int) i;
A(int j);
void v(int j);
};
// Storing to atomic values should be atomic
// CHECK: store atomic i32
void A::v(int j) { i = j; }
// Initialising atomic values should not be atomic
// CHECK-NOT: store atomic
A::A(int j) : i(j) {}
struct B {
int i;
B(int x) : i(x) {}
};
_Atomic(B) b;
// CHECK-LABEL: define void @_Z11atomic_initR1Ai
void atomic_init(A& a, int i) {
// CHECK-NOT: atomic
// CHECK: tail call void @_ZN1BC1Ei
__c11_atomic_init(&b, B(i));
// CHECK-NEXT: ret void
}
// CHECK-LABEL: define void @_Z16atomic_init_boolPU7_Atomicbb
void atomic_init_bool(_Atomic(bool) *ab, bool b) {
// CHECK-NOT: atomic
// CHECK: {{zext i1.*to i8}}
// CHECK-NEXT: store i8
__c11_atomic_init(ab, b);
// CHECK-NEXT: ret void
}
struct AtomicBoolMember {
_Atomic(bool) ab;
AtomicBoolMember(bool b);
};
// CHECK-LABEL: define void @_ZN16AtomicBoolMemberC2Eb
// CHECK: zext i1 {{.*}} to i8
// CHECK: store i8
// CHECK-NEXT: ret void
AtomicBoolMember::AtomicBoolMember(bool b) : ab(b) { }
namespace PR18097 {
namespace dynamic {
struct X {
X(int);
short n;
char c;
};
// CHECK-LABEL: define {{.*}} @__cxx_global_var_init
// CHECK: call void @_ZN7PR180977dynamic1XC1Ei({{.*}}* nonnull @_ZN7PR180977dynamic1aE, i32 1)
_Atomic(X) a = X(1);
// CHECK-LABEL: define {{.*}} @__cxx_global_var_init
// CHECK: call void @_ZN7PR180977dynamic1XC1Ei({{.*}}* nonnull @_ZN7PR180977dynamic1bE, i32 2)
_Atomic(X) b(X(2));
// CHECK-LABEL: define {{.*}} @__cxx_global_var_init
// CHECK: call void @_ZN7PR180977dynamic1XC1Ei({{.*}}* nonnull @_ZN7PR180977dynamic1cE, i32 3)
_Atomic(X) c{X(3)};
struct Y {
_Atomic(X) a;
_Atomic(int) b;
};
// CHECK-LABEL: define {{.*}} @__cxx_global_var_init
// CHECK: call void @_ZN7PR180977dynamic1XC1Ei({{.*}}* getelementptr inbounds ({{.*}}, {{.*}}* @_ZN7PR180977dynamic1yE, i32 0, i32 0), i32 4)
// CHECK: store i32 5, i32* getelementptr inbounds ({{.*}}, {{.*}}* @_ZN7PR180977dynamic1yE, i32 0, i32 1)
Y y = { X(4), 5 };
}
// CHECKs at top of file.
namespace constant {
struct X {
constexpr X(int n) : n(n) {}
short n;
char c = 6;
};
_Atomic(X) a = X(1);
_Atomic(X) b(X(2));
_Atomic(X) c{X(3)};
struct Y {
_Atomic(X) a;
_Atomic(int) b;
};
Y y = { X(4), 5 };
}
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* writerperfect
* Version: MPL 2.0 / LGPLv2.1+
*
* 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/.
*
* Major Contributor(s):
* Copyright (C) 2002-2004 William Lachance (wrlach@gmail.com)
* Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License Version 2.1 or later
* (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
* applicable instead of those above.
*
* For further information visit http://libwpd.sourceforge.net
*/
#include <string.h>
#include "StringDocumentHandler.hxx"
StringDocumentHandler::StringDocumentHandler() : m_data(""), m_isTagOpened(false), m_openedTagName("")
{
m_data.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
}
void StringDocumentHandler::endDocument()
{
if (!m_isTagOpened) return;
m_data.append(">");
m_isTagOpened = false;
}
void StringDocumentHandler::startElement(const char *psName, const librevenge::RVNGPropertyList &xPropList)
{
if (m_isTagOpened)
{
m_data.append(">");
m_isTagOpened = false;
}
m_data.append("<");
m_data.append(psName);
librevenge::RVNGPropertyList::Iter i(xPropList);
for (i.rewind(); i.next();)
{
// filter out librevenge elements
if (!strncmp(i.key(), "librevenge:", 11)) continue;
m_data.append(" ");
m_data.append(i.key());
m_data.append("=\"");
if (i()->getStr().len()>0)
m_data.append(i()->getStr().cstr());
m_data.append("\"");
}
m_isTagOpened = true;
m_openedTagName.sprintf("%s", psName);
}
void StringDocumentHandler::endElement(const char *psName)
{
if (m_isTagOpened)
{
if (m_openedTagName == psName)
{
m_data.append("/>");
m_isTagOpened = false;
}
else // should not happen, but handle it
{
m_data.append(">");
m_data.append("</");
m_data.append(psName);
m_data.append(">");
m_isTagOpened = false;
}
}
else
{
m_data.append("</");
m_data.append(psName);
m_data.append(">");
m_isTagOpened = false;
}
}
void StringDocumentHandler::characters(const librevenge::RVNGString &sCharacters)
{
if (m_isTagOpened)
{
m_data.append(">");
m_isTagOpened = false;
}
librevenge::RVNGString sEscapedCharacters(sCharacters, true);
if (sEscapedCharacters.len() > 0)
m_data.append(sEscapedCharacters.cstr());
}
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<commit_msg>One more change in RVNGString<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* writerperfect
* Version: MPL 2.0 / LGPLv2.1+
*
* 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/.
*
* Major Contributor(s):
* Copyright (C) 2002-2004 William Lachance (wrlach@gmail.com)
* Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License Version 2.1 or later
* (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
* applicable instead of those above.
*
* For further information visit http://libwpd.sourceforge.net
*/
#include <string.h>
#include "StringDocumentHandler.hxx"
StringDocumentHandler::StringDocumentHandler() : m_data(""), m_isTagOpened(false), m_openedTagName("")
{
m_data.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
}
void StringDocumentHandler::endDocument()
{
if (!m_isTagOpened) return;
m_data.append(">");
m_isTagOpened = false;
}
void StringDocumentHandler::startElement(const char *psName, const librevenge::RVNGPropertyList &xPropList)
{
if (m_isTagOpened)
{
m_data.append(">");
m_isTagOpened = false;
}
m_data.append("<");
m_data.append(psName);
librevenge::RVNGPropertyList::Iter i(xPropList);
for (i.rewind(); i.next();)
{
// filter out librevenge elements
if (!strncmp(i.key(), "librevenge:", 11)) continue;
m_data.append(" ");
m_data.append(i.key());
m_data.append("=\"");
if (i()->getStr().len()>0)
m_data.append(i()->getStr().cstr());
m_data.append("\"");
}
m_isTagOpened = true;
m_openedTagName.sprintf("%s", psName);
}
void StringDocumentHandler::endElement(const char *psName)
{
if (m_isTagOpened)
{
if (m_openedTagName == psName)
{
m_data.append("/>");
m_isTagOpened = false;
}
else // should not happen, but handle it
{
m_data.append(">");
m_data.append("</");
m_data.append(psName);
m_data.append(">");
m_isTagOpened = false;
}
}
else
{
m_data.append("</");
m_data.append(psName);
m_data.append(">");
m_isTagOpened = false;
}
}
void StringDocumentHandler::characters(const librevenge::RVNGString &sCharacters)
{
if (m_isTagOpened)
{
m_data.append(">");
m_isTagOpened = false;
}
librevenge::RVNGString sEscapedCharacters;
sEscapedCharacters.appendEscapedXML(sCharacters)
if (sEscapedCharacters.len() > 0)
m_data.append(sEscapedCharacters.cstr());
}
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
<|endoftext|>
|
<commit_before>/**
* @file edge.cpp
* @brief Simple test for OpenCV
* @author Denis Deryugin <deryugin.denis@gmail.com>
* @version
* @date 03.06.2019
*/
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
#include <drivers/video/fb.h>
using namespace cv;
using namespace std;
static void help(void) {
printf("\nThis sample demonstrates Canny edge detection\n"
"Call:\n"
" ./edge [image [threshold]] \n\n");
}
static const char* keys = {
"{help h||}"
"{@image | \"fruits.png\" | source image }"
"{@repeat |1 | number}"
};
int main(int argc, const char** argv) {
int edgeThresh = 2;
Mat image, gray, edge, cedge;
struct fb_info *fbi = fb_lookup(0);
CommandLineParser parser(argc, argv, keys);
if (parser.has("help")) {
help();
return 0;
}
edgeThresh = parser.get<int>(1);
string filename = parser.get<String>("@image");
image = imread(filename, 1);
if(image.empty()) {
printf("Cannot read image file: %s\n", filename.c_str());
help();
return -1;
}
cedge.create(image.size(), image.type());
cvtColor(image, gray, COLOR_BGR2GRAY);
blur(gray, edge, Size(3,3));
Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
cedge = Scalar::all(0);
image.copyTo(cedge, edge);
printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel);
printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh);
for (int y = 0; y < cedge.rows; y++) {
const uchar *row = &cedge.at<uchar>(y, 0);
for (int x = 0; x < 3 * cedge.cols; x += 3) {
unsigned rgb888 =
0xFF000000 |
unsigned(row[x]) |
(unsigned(row[x + 1]) << 8) |
(unsigned(row[x + 2]) << 16);
((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x / 3] = rgb888;
}
}
return 0;
}
<commit_msg>opencv: Extract fb drawing to a function in edges.cpp<commit_after>/**
* @file edge.cpp
* @brief Simple test for OpenCV
* @author Denis Deryugin <deryugin.denis@gmail.com>
* @version
* @date 03.06.2019
*/
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>
#include <drivers/video/fb.h>
using namespace cv;
using namespace std;
static void help(void) {
printf("\nThis sample demonstrates Canny edge detection\n"
"Call:\n"
" ./edge [image [threshold]] \n\n");
}
static const char* keys = {
"{help h||}"
"{@image | \"fruits.png\" | source image }"
"{@repeat |1 | number}"
};
static void imdrawfb(Mat& img) {
struct fb_info *fbi;
int w, h;
fbi = fb_lookup(0);
if (!fbi) {
printf("fb0 not found\n");
return;
}
printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel);
h = min((int) fbi->var.yres, img.rows);
w = min((int) (fbi->var.bits_per_pixel * fbi->var.xres) / 8, 3 * img.cols);
for (int y = 0; y < h; y++) {
const uchar *row = &img.at<uchar>(y, 0);
for (int x = 0; x < w; x += 3) {
unsigned rgb888 =
0xFF000000 |
unsigned(row[x]) |
(unsigned(row[x + 1]) << 8) |
(unsigned(row[x + 2]) << 16);
((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x / 3] = rgb888;
}
}
}
int main(int argc, const char** argv) {
int edgeThresh = 2;
Mat image, gray, edge, cedge;
CommandLineParser parser(argc, argv, keys);
if (parser.has("help")) {
help();
return 0;
}
edgeThresh = parser.get<int>(1);
string filename = parser.get<String>("@image");
image = imread(filename, 1);
if(image.empty()) {
printf("Cannot read image file: %s\n", filename.c_str());
help();
return -1;
}
cedge.create(image.size(), image.type());
cvtColor(image, gray, COLOR_BGR2GRAY);
blur(gray, edge, Size(3,3));
Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
cedge = Scalar::all(0);
image.copyTo(cedge, edge);
printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh);
imdrawfb(cedge);
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/url_fetcher.h"
#include "base/compiler_specific.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/net/url_request_context_getter.h"
#include "googleurl/src/gurl.h"
#include "net/base/load_flags.h"
#include "net/base/io_buffer.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
static const int kBufferSize = 4096;
bool URLFetcher::g_interception_enabled = false;
class URLFetcher::Core
: public base::RefCountedThreadSafe<URLFetcher::Core>,
public URLRequest::Delegate {
public:
// For POST requests, set |content_type| to the MIME type of the content
// and set |content| to the data to upload. |flags| are flags to apply to
// the load operation--these should be one or more of the LOAD_* flags
// defined in url_request.h.
Core(URLFetcher* fetcher,
const GURL& original_url,
RequestType request_type,
URLFetcher::Delegate* d);
// Starts the load. It's important that this not happen in the constructor
// because it causes the IO thread to begin AddRef()ing and Release()ing
// us. If our caller hasn't had time to fully construct us and take a
// reference, the IO thread could interrupt things, run a task, Release()
// us, and destroy us, leaving the caller with an already-destroyed object
// when construction finishes.
void Start();
// Stops any in-progress load and ensures no callback will happen. It is
// safe to call this multiple times.
void Stop();
// URLRequest::Delegate implementations
virtual void OnResponseStarted(URLRequest* request);
virtual void OnReadCompleted(URLRequest* request, int bytes_read);
URLFetcher::Delegate* delegate() const { return delegate_; }
private:
friend class base::RefCountedThreadSafe<URLFetcher::Core>;
~Core() {}
// Wrapper functions that allow us to ensure actions happen on the right
// thread.
void StartURLRequest();
void CancelURLRequest();
void OnCompletedURLRequest(const URLRequestStatus& status);
URLFetcher* fetcher_; // Corresponding fetcher object
GURL original_url_; // The URL we were asked to fetch
GURL url_; // The URL we eventually wound up at
RequestType request_type_; // What type of request is this?
URLFetcher::Delegate* delegate_; // Object to notify on completion
MessageLoop* delegate_loop_; // Message loop of the creating thread
URLRequest* request_; // The actual request this wraps
int load_flags_; // Flags for the load operation
int response_code_; // HTTP status code for the request
std::string data_; // Results of the request
scoped_refptr<net::IOBuffer> buffer_;
// Read buffer
scoped_refptr<URLRequestContextGetter> request_context_getter_;
// Cookie/cache info for the request
ResponseCookies cookies_; // Response cookies
std::string extra_request_headers_;// Extra headers for the request, if any
scoped_refptr<net::HttpResponseHeaders> response_headers_;
std::string upload_content_; // HTTP POST payload
std::string upload_content_type_; // MIME type of POST payload
// The overload protection entry for this URL. This is used to
// incrementally back off how rapidly we'll send requests to a particular
// URL, to avoid placing too much demand on the remote resource. We update
// this with the status of all requests as they return, and in turn use it
// to determine how long to wait before making another request.
URLFetcherProtectEntry* protect_entry_;
// |num_retries_| indicates how many times we've failed to successfully
// fetch this URL. Once this value exceeds the maximum number of retries
// specified by the protection manager, we'll give up.
int num_retries_;
friend class URLFetcher;
DISALLOW_COPY_AND_ASSIGN(Core);
};
// static
URLFetcher::Factory* URLFetcher::factory_ = NULL;
URLFetcher::URLFetcher(const GURL& url,
RequestType request_type,
Delegate* d)
: ALLOW_THIS_IN_INITIALIZER_LIST(
core_(new Core(this, url, request_type, d))) {
}
URLFetcher::~URLFetcher() {
core_->Stop();
}
// static
URLFetcher* URLFetcher::Create(int id, const GURL& url,
RequestType request_type, Delegate* d) {
return factory_ ? factory_->CreateURLFetcher(id, url, request_type, d) :
new URLFetcher(url, request_type, d);
}
URLFetcher::Core::Core(URLFetcher* fetcher,
const GURL& original_url,
RequestType request_type,
URLFetcher::Delegate* d)
: fetcher_(fetcher),
original_url_(original_url),
request_type_(request_type),
delegate_(d),
delegate_loop_(MessageLoop::current()),
request_(NULL),
load_flags_(net::LOAD_NORMAL),
response_code_(-1),
buffer_(new net::IOBuffer(kBufferSize)),
protect_entry_(URLFetcherProtectManager::GetInstance()->Register(
original_url_.host())),
num_retries_(0) {
}
void URLFetcher::Core::Start() {
DCHECK(delegate_loop_);
DCHECK(request_context_getter_) << "We need an URLRequestContext!";
ChromeThread::PostDelayedTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &Core::StartURLRequest),
protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SEND));
}
void URLFetcher::Core::Stop() {
DCHECK_EQ(MessageLoop::current(), delegate_loop_);
delegate_ = NULL;
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &Core::CancelURLRequest));
}
void URLFetcher::Core::OnResponseStarted(URLRequest* request) {
DCHECK(request == request_);
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
if (request_->status().is_success()) {
response_code_ = request_->GetResponseCode();
response_headers_ = request_->response_headers();
}
int bytes_read = 0;
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
if (request_->status().is_success() && (request_type_ != HEAD))
request_->Read(buffer_, kBufferSize, &bytes_read);
OnReadCompleted(request_, bytes_read);
}
void URLFetcher::Core::OnReadCompleted(URLRequest* request, int bytes_read) {
DCHECK(request == request_);
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
url_ = request->url();
do {
if (!request_->status().is_success() || bytes_read <= 0)
break;
data_.append(buffer_->data(), bytes_read);
} while (request_->Read(buffer_, kBufferSize, &bytes_read));
if (request_->status().is_success())
request_->GetResponseCookies(&cookies_);
// See comments re: HEAD requests in OnResponseStarted().
if (!request_->status().is_io_pending() || (request_type_ == HEAD)) {
delegate_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Core::OnCompletedURLRequest, request_->status()));
delete request_;
request_ = NULL;
}
}
void URLFetcher::Core::StartURLRequest() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
DCHECK(!request_);
request_ = new URLRequest(original_url_, this);
int flags = request_->load_flags() | load_flags_;
if (!g_interception_enabled) {
flags = flags | net::LOAD_DISABLE_INTERCEPT;
}
request_->set_load_flags(flags);
request_->set_context(request_context_getter_->GetURLRequestContext());
switch (request_type_) {
case GET:
break;
case POST:
DCHECK(!upload_content_.empty());
DCHECK(!upload_content_type_.empty());
request_->set_method("POST");
if (!extra_request_headers_.empty())
extra_request_headers_ += "\r\n";
StringAppendF(&extra_request_headers_,
"Content-Type: %s", upload_content_type_.c_str());
request_->AppendBytesToUpload(upload_content_.data(),
static_cast<int>(upload_content_.size()));
break;
case HEAD:
request_->set_method("HEAD");
break;
default:
NOTREACHED();
}
if (!extra_request_headers_.empty())
request_->SetExtraRequestHeaders(extra_request_headers_);
request_->Start();
}
void URLFetcher::Core::CancelURLRequest() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
if (request_) {
request_->Cancel();
delete request_;
request_ = NULL;
}
// Release the reference to the request context. There could be multiple
// references to URLFetcher::Core at this point so it may take a while to
// delete the object, but we cannot delay the destruction of the request
// context.
request_context_getter_ = NULL;
}
void URLFetcher::Core::OnCompletedURLRequest(const URLRequestStatus& status) {
DCHECK(MessageLoop::current() == delegate_loop_);
// Checks the response from server.
if (response_code_ >= 500) {
// When encountering a server error, we will send the request again
// after backoff time.
const int64 wait =
protect_entry_->UpdateBackoff(URLFetcherProtectEntry::FAILURE);
++num_retries_;
// Restarts the request if we still need to notify the delegate.
if (delegate_) {
if (num_retries_ <= protect_entry_->max_retries()) {
ChromeThread::PostDelayedTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &Core::StartURLRequest), wait);
} else {
delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_,
cookies_, data_);
}
}
} else {
protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SUCCESS);
if (delegate_)
delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_,
cookies_, data_);
}
}
void URLFetcher::set_upload_data(const std::string& upload_content_type,
const std::string& upload_content) {
core_->upload_content_type_ = upload_content_type;
core_->upload_content_ = upload_content;
}
void URLFetcher::set_load_flags(int load_flags) {
core_->load_flags_ = load_flags;
}
int URLFetcher::load_flags() const {
return core_->load_flags_;
}
void URLFetcher::set_extra_request_headers(
const std::string& extra_request_headers) {
core_->extra_request_headers_ = extra_request_headers;
}
void URLFetcher::set_request_context(
URLRequestContextGetter* request_context_getter) {
core_->request_context_getter_ = request_context_getter;
}
net::HttpResponseHeaders* URLFetcher::response_headers() const {
return core_->response_headers_;
}
void URLFetcher::Start() {
core_->Start();
}
const GURL& URLFetcher::url() const {
return core_->url_;
}
URLFetcher::Delegate* URLFetcher::delegate() const {
return core_->delegate();
}
<commit_msg>Add instrumentation to track down a crash.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/net/url_fetcher.h"
#include "base/compiler_specific.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/net/url_request_context_getter.h"
#include "googleurl/src/gurl.h"
#include "net/base/load_flags.h"
#include "net/base/io_buffer.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
static const int kBufferSize = 4096;
bool URLFetcher::g_interception_enabled = false;
class URLFetcher::Core
: public base::RefCountedThreadSafe<URLFetcher::Core>,
public URLRequest::Delegate {
public:
// For POST requests, set |content_type| to the MIME type of the content
// and set |content| to the data to upload. |flags| are flags to apply to
// the load operation--these should be one or more of the LOAD_* flags
// defined in url_request.h.
Core(URLFetcher* fetcher,
const GURL& original_url,
RequestType request_type,
URLFetcher::Delegate* d);
// Starts the load. It's important that this not happen in the constructor
// because it causes the IO thread to begin AddRef()ing and Release()ing
// us. If our caller hasn't had time to fully construct us and take a
// reference, the IO thread could interrupt things, run a task, Release()
// us, and destroy us, leaving the caller with an already-destroyed object
// when construction finishes.
void Start();
// Stops any in-progress load and ensures no callback will happen. It is
// safe to call this multiple times.
void Stop();
// URLRequest::Delegate implementations
virtual void OnResponseStarted(URLRequest* request);
virtual void OnReadCompleted(URLRequest* request, int bytes_read);
URLFetcher::Delegate* delegate() const { return delegate_; }
private:
friend class base::RefCountedThreadSafe<URLFetcher::Core>;
~Core() {}
// Wrapper functions that allow us to ensure actions happen on the right
// thread.
void StartURLRequest();
void CancelURLRequest();
void OnCompletedURLRequest(const URLRequestStatus& status);
URLFetcher* fetcher_; // Corresponding fetcher object
GURL original_url_; // The URL we were asked to fetch
GURL url_; // The URL we eventually wound up at
RequestType request_type_; // What type of request is this?
URLFetcher::Delegate* delegate_; // Object to notify on completion
MessageLoop* delegate_loop_; // Message loop of the creating thread
URLRequest* request_; // The actual request this wraps
int load_flags_; // Flags for the load operation
int response_code_; // HTTP status code for the request
std::string data_; // Results of the request
scoped_refptr<net::IOBuffer> buffer_;
// Read buffer
scoped_refptr<URLRequestContextGetter> request_context_getter_;
// Cookie/cache info for the request
ResponseCookies cookies_; // Response cookies
std::string extra_request_headers_;// Extra headers for the request, if any
scoped_refptr<net::HttpResponseHeaders> response_headers_;
std::string upload_content_; // HTTP POST payload
std::string upload_content_type_; // MIME type of POST payload
// The overload protection entry for this URL. This is used to
// incrementally back off how rapidly we'll send requests to a particular
// URL, to avoid placing too much demand on the remote resource. We update
// this with the status of all requests as they return, and in turn use it
// to determine how long to wait before making another request.
URLFetcherProtectEntry* protect_entry_;
// |num_retries_| indicates how many times we've failed to successfully
// fetch this URL. Once this value exceeds the maximum number of retries
// specified by the protection manager, we'll give up.
int num_retries_;
// Temporary member variable to test whether requests are being started
// after they have already been cancelled.
// TODO(eroman): Remove this after done investigating 27074.
bool was_cancelled_;
friend class URLFetcher;
DISALLOW_COPY_AND_ASSIGN(Core);
};
// static
URLFetcher::Factory* URLFetcher::factory_ = NULL;
URLFetcher::URLFetcher(const GURL& url,
RequestType request_type,
Delegate* d)
: ALLOW_THIS_IN_INITIALIZER_LIST(
core_(new Core(this, url, request_type, d))) {
}
URLFetcher::~URLFetcher() {
core_->Stop();
}
// static
URLFetcher* URLFetcher::Create(int id, const GURL& url,
RequestType request_type, Delegate* d) {
return factory_ ? factory_->CreateURLFetcher(id, url, request_type, d) :
new URLFetcher(url, request_type, d);
}
URLFetcher::Core::Core(URLFetcher* fetcher,
const GURL& original_url,
RequestType request_type,
URLFetcher::Delegate* d)
: fetcher_(fetcher),
original_url_(original_url),
request_type_(request_type),
delegate_(d),
delegate_loop_(MessageLoop::current()),
request_(NULL),
load_flags_(net::LOAD_NORMAL),
response_code_(-1),
buffer_(new net::IOBuffer(kBufferSize)),
protect_entry_(URLFetcherProtectManager::GetInstance()->Register(
original_url_.host())),
num_retries_(0),
was_cancelled_(false) {
}
void URLFetcher::Core::Start() {
DCHECK(delegate_loop_);
CHECK(request_context_getter_) << "We need an URLRequestContext!";
ChromeThread::PostDelayedTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &Core::StartURLRequest),
protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SEND));
}
void URLFetcher::Core::Stop() {
DCHECK_EQ(MessageLoop::current(), delegate_loop_);
delegate_ = NULL;
ChromeThread::PostTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &Core::CancelURLRequest));
}
void URLFetcher::Core::OnResponseStarted(URLRequest* request) {
DCHECK(request == request_);
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
if (request_->status().is_success()) {
response_code_ = request_->GetResponseCode();
response_headers_ = request_->response_headers();
}
int bytes_read = 0;
// Some servers may treat HEAD requests as GET requests. To free up the
// network connection as soon as possible, signal that the request has
// completed immediately, without trying to read any data back (all we care
// about is the response code and headers, which we already have).
if (request_->status().is_success() && (request_type_ != HEAD))
request_->Read(buffer_, kBufferSize, &bytes_read);
OnReadCompleted(request_, bytes_read);
}
void URLFetcher::Core::OnReadCompleted(URLRequest* request, int bytes_read) {
DCHECK(request == request_);
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
url_ = request->url();
do {
if (!request_->status().is_success() || bytes_read <= 0)
break;
data_.append(buffer_->data(), bytes_read);
} while (request_->Read(buffer_, kBufferSize, &bytes_read));
if (request_->status().is_success())
request_->GetResponseCookies(&cookies_);
// See comments re: HEAD requests in OnResponseStarted().
if (!request_->status().is_io_pending() || (request_type_ == HEAD)) {
delegate_loop_->PostTask(FROM_HERE, NewRunnableMethod(
this, &Core::OnCompletedURLRequest, request_->status()));
delete request_;
request_ = NULL;
}
}
void URLFetcher::Core::StartURLRequest() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
CHECK(!was_cancelled_);
CHECK(request_context_getter_);
CHECK(!request_);
request_ = new URLRequest(original_url_, this);
int flags = request_->load_flags() | load_flags_;
if (!g_interception_enabled) {
flags = flags | net::LOAD_DISABLE_INTERCEPT;
}
request_->set_load_flags(flags);
request_->set_context(request_context_getter_->GetURLRequestContext());
switch (request_type_) {
case GET:
break;
case POST:
DCHECK(!upload_content_.empty());
DCHECK(!upload_content_type_.empty());
request_->set_method("POST");
if (!extra_request_headers_.empty())
extra_request_headers_ += "\r\n";
StringAppendF(&extra_request_headers_,
"Content-Type: %s", upload_content_type_.c_str());
request_->AppendBytesToUpload(upload_content_.data(),
static_cast<int>(upload_content_.size()));
break;
case HEAD:
request_->set_method("HEAD");
break;
default:
NOTREACHED();
}
if (!extra_request_headers_.empty())
request_->SetExtraRequestHeaders(extra_request_headers_);
request_->Start();
}
void URLFetcher::Core::CancelURLRequest() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
if (request_) {
request_->Cancel();
delete request_;
request_ = NULL;
}
// Release the reference to the request context. There could be multiple
// references to URLFetcher::Core at this point so it may take a while to
// delete the object, but we cannot delay the destruction of the request
// context.
request_context_getter_ = NULL;
was_cancelled_ = true;
}
void URLFetcher::Core::OnCompletedURLRequest(const URLRequestStatus& status) {
DCHECK(MessageLoop::current() == delegate_loop_);
// Checks the response from server.
if (response_code_ >= 500) {
// When encountering a server error, we will send the request again
// after backoff time.
const int64 wait =
protect_entry_->UpdateBackoff(URLFetcherProtectEntry::FAILURE);
++num_retries_;
// Restarts the request if we still need to notify the delegate.
if (delegate_) {
if (num_retries_ <= protect_entry_->max_retries()) {
ChromeThread::PostDelayedTask(
ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this, &Core::StartURLRequest), wait);
} else {
delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_,
cookies_, data_);
}
}
} else {
protect_entry_->UpdateBackoff(URLFetcherProtectEntry::SUCCESS);
if (delegate_)
delegate_->OnURLFetchComplete(fetcher_, url_, status, response_code_,
cookies_, data_);
}
}
void URLFetcher::set_upload_data(const std::string& upload_content_type,
const std::string& upload_content) {
core_->upload_content_type_ = upload_content_type;
core_->upload_content_ = upload_content;
}
void URLFetcher::set_load_flags(int load_flags) {
core_->load_flags_ = load_flags;
}
int URLFetcher::load_flags() const {
return core_->load_flags_;
}
void URLFetcher::set_extra_request_headers(
const std::string& extra_request_headers) {
core_->extra_request_headers_ = extra_request_headers;
}
void URLFetcher::set_request_context(
URLRequestContextGetter* request_context_getter) {
core_->request_context_getter_ = request_context_getter;
}
net::HttpResponseHeaders* URLFetcher::response_headers() const {
return core_->response_headers_;
}
void URLFetcher::Start() {
core_->Start();
}
const GURL& URLFetcher::url() const {
return core_->url_;
}
URLFetcher::Delegate* URLFetcher::delegate() const {
return core_->delegate();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/page_menu_model.h"
#include "app/l10n_util.h"
#include "base/compiler_specific.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/encoding_menu_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
PageMenuModel::PageMenuModel(menus::SimpleMenuModel::Delegate* delegate,
Browser* browser)
: menus::SimpleMenuModel(delegate), browser_(browser) {
Build();
}
void PageMenuModel::Build() {
#if !defined(OS_CHROMEOS)
#if defined(OS_MACOSX)
AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_APPLICATION_MAC);
#else
AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_SHORTCUTS);
#endif
AddSeparator();
#endif
AddItemWithStringId(IDC_CUT, IDS_CUT);
AddItemWithStringId(IDC_COPY, IDS_COPY);
AddItemWithStringId(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItemWithStringId(IDC_FIND, IDS_FIND);
AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE);
AddItemWithStringId(IDC_PRINT, IDS_PRINT);
AddSeparator();
zoom_menu_model_.reset(new ZoomMenuModel(delegate()));
AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get());
encoding_menu_model_.reset(new EncodingMenuModel(browser_));
AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU,
encoding_menu_model_.get());
AddSeparator();
devtools_menu_model_.reset(new DevToolsMenuModel(delegate()));
AddSubMenuWithStringId(IDC_DEVELOPER_MENU, IDS_DEVELOPER_MENU,
devtools_menu_model_.get());
AddSeparator();
AddItemWithStringId(IDC_REPORT_BUG, IDS_REPORT_BUG);
}
////////////////////////////////////////////////////////////////////////////////
// EncodingMenuModel
EncodingMenuModel::EncodingMenuModel(Browser* browser)
: ALLOW_THIS_IN_INITIALIZER_LIST(menus::SimpleMenuModel(this)),
browser_(browser) {
Build();
}
void EncodingMenuModel::Build() {
EncodingMenuController::EncodingMenuItemList encoding_menu_items;
EncodingMenuController encoding_menu_controller;
encoding_menu_controller.GetEncodingMenuItems(browser_->profile(),
&encoding_menu_items);
int group_id = 0;
EncodingMenuController::EncodingMenuItemList::iterator it =
encoding_menu_items.begin();
for (; it != encoding_menu_items.end(); ++it) {
int id = it->first;
string16& label = it->second;
if (id == 0) {
AddSeparator();
} else {
if (id == IDC_ENCODING_AUTO_DETECT) {
AddCheckItem(id, label);
} else {
// Use the id of the first radio command as the id of the group.
if (group_id <= 0)
group_id = id;
AddRadioItem(id, label, group_id);
}
}
}
}
bool EncodingMenuModel::IsCommandIdChecked(int command_id) const {
TabContents* current_tab = browser_->GetSelectedTabContents();
if (!current_tab)
return false;
EncodingMenuController controller;
return controller.IsItemChecked(browser_->profile(),
current_tab->encoding(), command_id);
}
bool EncodingMenuModel::IsCommandIdEnabled(int command_id) const {
return browser_->command_updater()->IsCommandEnabled(command_id);
}
bool EncodingMenuModel::GetAcceleratorForCommandId(
int command_id,
menus::Accelerator* accelerator) {
return false;
}
void EncodingMenuModel::ExecuteCommand(int command_id) {
browser_->ExecuteCommand(command_id);
}
////////////////////////////////////////////////////////////////////////////////
// ZoomMenuModel
ZoomMenuModel::ZoomMenuModel(menus::SimpleMenuModel::Delegate* delegate)
: SimpleMenuModel(delegate) {
Build();
}
void ZoomMenuModel::Build() {
AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS);
AddItemWithStringId(IDC_ZOOM_NORMAL, IDS_ZOOM_NORMAL);
AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS);
}
////////////////////////////////////////////////////////////////////////////////
// DevToolsMenuModel
DevToolsMenuModel::DevToolsMenuModel(menus::SimpleMenuModel::Delegate* delegate)
: SimpleMenuModel(delegate) {
Build();
}
void DevToolsMenuModel::Build() {
AddItemWithStringId(IDC_VIEW_SOURCE, IDS_VIEW_SOURCE);
if (g_browser_process->have_inspector_files()) {
AddItemWithStringId(IDC_DEV_TOOLS, IDS_DEV_TOOLS);
AddItemWithStringId(IDC_DEV_TOOLS_CONSOLE, IDS_DEV_TOOLS_CONSOLE);
}
AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER);
}
////////////////////////////////////////////////////////////////////////////////
// PopupPageMenuModel
PopupPageMenuModel::PopupPageMenuModel(
menus::SimpleMenuModel::Delegate* delegate,
Browser* browser)
: menus::SimpleMenuModel(delegate), browser_(browser) {
Build();
}
void PopupPageMenuModel::Build() {
AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK);
AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD);
AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD);
AddSeparator();
AddItemWithStringId(IDC_CUT, IDS_CUT);
AddItemWithStringId(IDC_COPY, IDS_COPY);
AddItemWithStringId(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItemWithStringId(IDC_FIND, IDS_FIND);
AddItemWithStringId(IDC_PRINT, IDS_PRINT);
zoom_menu_model_.reset(new ZoomMenuModel(delegate()));
AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get());
encoding_menu_model_.reset(new EncodingMenuModel(browser_));
AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU,
encoding_menu_model_.get());
}
<commit_msg>GTK: Add "Show as Tab" to popup windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/page_menu_model.h"
#include "app/l10n_util.h"
#include "base/compiler_specific.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/encoding_menu_controller.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "grit/generated_resources.h"
PageMenuModel::PageMenuModel(menus::SimpleMenuModel::Delegate* delegate,
Browser* browser)
: menus::SimpleMenuModel(delegate), browser_(browser) {
Build();
}
void PageMenuModel::Build() {
#if !defined(OS_CHROMEOS)
#if defined(OS_MACOSX)
AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_APPLICATION_MAC);
#else
AddItemWithStringId(IDC_CREATE_SHORTCUTS, IDS_CREATE_SHORTCUTS);
#endif
AddSeparator();
#endif
AddItemWithStringId(IDC_CUT, IDS_CUT);
AddItemWithStringId(IDC_COPY, IDS_COPY);
AddItemWithStringId(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItemWithStringId(IDC_FIND, IDS_FIND);
AddItemWithStringId(IDC_SAVE_PAGE, IDS_SAVE_PAGE);
AddItemWithStringId(IDC_PRINT, IDS_PRINT);
AddSeparator();
zoom_menu_model_.reset(new ZoomMenuModel(delegate()));
AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get());
encoding_menu_model_.reset(new EncodingMenuModel(browser_));
AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU,
encoding_menu_model_.get());
AddSeparator();
devtools_menu_model_.reset(new DevToolsMenuModel(delegate()));
AddSubMenuWithStringId(IDC_DEVELOPER_MENU, IDS_DEVELOPER_MENU,
devtools_menu_model_.get());
AddSeparator();
AddItemWithStringId(IDC_REPORT_BUG, IDS_REPORT_BUG);
}
////////////////////////////////////////////////////////////////////////////////
// EncodingMenuModel
EncodingMenuModel::EncodingMenuModel(Browser* browser)
: ALLOW_THIS_IN_INITIALIZER_LIST(menus::SimpleMenuModel(this)),
browser_(browser) {
Build();
}
void EncodingMenuModel::Build() {
EncodingMenuController::EncodingMenuItemList encoding_menu_items;
EncodingMenuController encoding_menu_controller;
encoding_menu_controller.GetEncodingMenuItems(browser_->profile(),
&encoding_menu_items);
int group_id = 0;
EncodingMenuController::EncodingMenuItemList::iterator it =
encoding_menu_items.begin();
for (; it != encoding_menu_items.end(); ++it) {
int id = it->first;
string16& label = it->second;
if (id == 0) {
AddSeparator();
} else {
if (id == IDC_ENCODING_AUTO_DETECT) {
AddCheckItem(id, label);
} else {
// Use the id of the first radio command as the id of the group.
if (group_id <= 0)
group_id = id;
AddRadioItem(id, label, group_id);
}
}
}
}
bool EncodingMenuModel::IsCommandIdChecked(int command_id) const {
TabContents* current_tab = browser_->GetSelectedTabContents();
if (!current_tab)
return false;
EncodingMenuController controller;
return controller.IsItemChecked(browser_->profile(),
current_tab->encoding(), command_id);
}
bool EncodingMenuModel::IsCommandIdEnabled(int command_id) const {
return browser_->command_updater()->IsCommandEnabled(command_id);
}
bool EncodingMenuModel::GetAcceleratorForCommandId(
int command_id,
menus::Accelerator* accelerator) {
return false;
}
void EncodingMenuModel::ExecuteCommand(int command_id) {
browser_->ExecuteCommand(command_id);
}
////////////////////////////////////////////////////////////////////////////////
// ZoomMenuModel
ZoomMenuModel::ZoomMenuModel(menus::SimpleMenuModel::Delegate* delegate)
: SimpleMenuModel(delegate) {
Build();
}
void ZoomMenuModel::Build() {
AddItemWithStringId(IDC_ZOOM_PLUS, IDS_ZOOM_PLUS);
AddItemWithStringId(IDC_ZOOM_NORMAL, IDS_ZOOM_NORMAL);
AddItemWithStringId(IDC_ZOOM_MINUS, IDS_ZOOM_MINUS);
}
////////////////////////////////////////////////////////////////////////////////
// DevToolsMenuModel
DevToolsMenuModel::DevToolsMenuModel(menus::SimpleMenuModel::Delegate* delegate)
: SimpleMenuModel(delegate) {
Build();
}
void DevToolsMenuModel::Build() {
AddItemWithStringId(IDC_VIEW_SOURCE, IDS_VIEW_SOURCE);
if (g_browser_process->have_inspector_files()) {
AddItemWithStringId(IDC_DEV_TOOLS, IDS_DEV_TOOLS);
AddItemWithStringId(IDC_DEV_TOOLS_CONSOLE, IDS_DEV_TOOLS_CONSOLE);
}
AddItemWithStringId(IDC_TASK_MANAGER, IDS_TASK_MANAGER);
}
////////////////////////////////////////////////////////////////////////////////
// PopupPageMenuModel
PopupPageMenuModel::PopupPageMenuModel(
menus::SimpleMenuModel::Delegate* delegate,
Browser* browser)
: menus::SimpleMenuModel(delegate), browser_(browser) {
Build();
}
void PopupPageMenuModel::Build() {
AddItemWithStringId(IDC_BACK, IDS_CONTENT_CONTEXT_BACK);
AddItemWithStringId(IDC_FORWARD, IDS_CONTENT_CONTEXT_FORWARD);
AddItemWithStringId(IDC_RELOAD, IDS_APP_MENU_RELOAD);
AddSeparator();
AddItemWithStringId(IDC_SHOW_AS_TAB, IDS_SHOW_AS_TAB);
AddSeparator();
AddItemWithStringId(IDC_CUT, IDS_CUT);
AddItemWithStringId(IDC_COPY, IDS_COPY);
AddItemWithStringId(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItemWithStringId(IDC_FIND, IDS_FIND);
AddItemWithStringId(IDC_PRINT, IDS_PRINT);
zoom_menu_model_.reset(new ZoomMenuModel(delegate()));
AddSubMenuWithStringId(IDC_ZOOM_MENU, IDS_ZOOM_MENU, zoom_menu_model_.get());
encoding_menu_model_.reset(new EncodingMenuModel(browser_));
AddSubMenuWithStringId(IDC_ENCODING_MENU, IDS_ENCODING_MENU,
encoding_menu_model_.get());
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_elf/blacklist/blacklist.h"
#include <string.h>
#include "base/basictypes.h"
#include "chrome_elf/blacklist/blacklist_interceptions.h"
#include "sandbox/win/src/interception_internal.h"
#include "sandbox/win/src/internal_types.h"
#include "sandbox/win/src/sandbox_utils.h"
#include "sandbox/win/src/service_resolver.h"
// http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
extern "C" IMAGE_DOS_HEADER __ImageBase;
namespace blacklist{
const wchar_t* g_troublesome_dlls[kTroublesomeDllsMaxCount] = {};
int g_troublesome_dlls_cur_index = 0;
const wchar_t kRegistryBeaconPath[] = L"SOFTWARE\\Google\\Chrome\\BLBeacon";
} // namespace blacklist
// Allocate storage for thunks in a RWX page of this module to save on doing
// an extra allocation at run time.
#if !defined(_WIN64) && (_MSC_VER < 1700)
// 64-bit images or images generated with 2012 and above appear to not support
// writeable and executable pages.
// This would yield compile warning C4330.
// TODO(robertshield): Figure out how / if to do this on 2012.
#pragma section(".crthunk",read,write,execute)
__declspec(allocate(".crthunk")) sandbox::ThunkData g_thunk_storage;
#endif
namespace {
enum Version {
VERSION_PRE_XP_SP2 = 0, // Not supported.
VERSION_XP_SP2,
VERSION_SERVER_2003, // Also includes XP Pro x64 and Server 2003 R2.
VERSION_VISTA, // Also includes Windows Server 2008.
VERSION_WIN7, // Also includes Windows Server 2008 R2.
VERSION_WIN8, // Also includes Windows Server 2012.
VERSION_WIN8_1,
VERSION_WIN_LAST, // Indicates error condition.
};
// Whether a process is running under WOW64 (the wrapper that allows 32-bit
// processes to run on 64-bit versions of Windows). This will return
// WOW64_DISABLED for both "32-bit Chrome on 32-bit Windows" and "64-bit
// Chrome on 64-bit Windows". WOW64_UNKNOWN means "an error occurred", e.g.
// the process does not have sufficient access rights to determine this.
enum WOW64Status {
WOW64_DISABLED,
WOW64_ENABLED,
WOW64_UNKNOWN,
};
WOW64Status GetWOW64StatusForCurrentProcess() {
typedef BOOL (WINAPI* IsWow64ProcessFunc)(HANDLE, PBOOL);
IsWow64ProcessFunc is_wow64_process = reinterpret_cast<IsWow64ProcessFunc>(
GetProcAddress(GetModuleHandle(L"kernel32.dll"), "IsWow64Process"));
if (!is_wow64_process)
return WOW64_DISABLED;
BOOL is_wow64 = FALSE;
if (!(*is_wow64_process)(GetCurrentProcess(), &is_wow64))
return WOW64_UNKNOWN;
return is_wow64 ? WOW64_ENABLED : WOW64_DISABLED;
}
class OSInfo {
public:
struct VersionNumber {
int major;
int minor;
int build;
};
struct ServicePack {
int major;
int minor;
};
OSInfo() {
OSVERSIONINFOEX version_info = { sizeof(version_info) };
GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&version_info));
version_number_.major = version_info.dwMajorVersion;
version_number_.minor = version_info.dwMinorVersion;
version_number_.build = version_info.dwBuildNumber;
if ((version_number_.major == 5) && (version_number_.minor > 0)) {
// Treat XP Pro x64, Home Server, and Server 2003 R2 as Server 2003.
version_ = (version_number_.minor == 1) ? VERSION_XP_SP2 :
VERSION_SERVER_2003;
if (version_ == VERSION_XP_SP2 && version_info.wServicePackMajor < 2)
version_ = VERSION_PRE_XP_SP2;
} else if (version_number_.major == 6) {
switch (version_number_.minor) {
case 0:
// Treat Windows Server 2008 the same as Windows Vista.
version_ = VERSION_VISTA;
break;
case 1:
// Treat Windows Server 2008 R2 the same as Windows 7.
version_ = VERSION_WIN7;
break;
case 2:
// Treat Windows Server 2012 the same as Windows 8.
version_ = VERSION_WIN8;
break;
default:
version_ = VERSION_WIN8_1;
break;
}
} else if (version_number_.major > 6) {
version_ = VERSION_WIN_LAST;
} else {
version_ = VERSION_PRE_XP_SP2;
}
service_pack_.major = version_info.wServicePackMajor;
service_pack_.minor = version_info.wServicePackMinor;
}
Version version() const { return version_; }
VersionNumber version_number() const { return version_number_; }
ServicePack service_pack() const { return service_pack_; }
private:
Version version_;
VersionNumber version_number_;
ServicePack service_pack_;
DISALLOW_COPY_AND_ASSIGN(OSInfo);
};
bool IsNonBrowserProcess() {
wchar_t* command_line = GetCommandLine();
return (command_line && wcsstr(command_line, L"--type"));
}
} // namespace
namespace blacklist {
bool CreateBeacon() {
HKEY beacon_key = NULL;
DWORD disposition = 0;
LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
kRegistryBeaconPath,
0,
NULL,
0,
KEY_WRITE,
NULL,
&beacon_key,
&disposition);
bool success = (result == ERROR_SUCCESS &&
disposition != REG_OPENED_EXISTING_KEY);
if (result == ERROR_SUCCESS)
::RegCloseKey(beacon_key);
return success;
}
bool ClearBeacon() {
LONG result = ::RegDeleteKey(HKEY_CURRENT_USER, kRegistryBeaconPath);
return (result == ERROR_SUCCESS);
}
bool AddDllToBlacklist(const wchar_t* dll_name) {
if (g_troublesome_dlls_cur_index >= kTroublesomeDllsMaxCount)
return false;
for (int i = 0; i < g_troublesome_dlls_cur_index; ++i) {
if (!wcscmp(g_troublesome_dlls[i], dll_name))
return true;
}
// Copy string to blacklist.
wchar_t* str_buffer = new wchar_t[wcslen(dll_name) + 1];
wcscpy(str_buffer, dll_name);
g_troublesome_dlls[g_troublesome_dlls_cur_index] = str_buffer;
g_troublesome_dlls_cur_index++;
return true;
}
bool RemoveDllFromBlacklist(const wchar_t* dll_name) {
for (int i = 0; i < g_troublesome_dlls_cur_index; ++i) {
if (!wcscmp(g_troublesome_dlls[i], dll_name)) {
// Found the thing to remove. Delete it then replace it with the last
// element.
g_troublesome_dlls_cur_index--;
delete[] g_troublesome_dlls[i];
g_troublesome_dlls[i] = g_troublesome_dlls[g_troublesome_dlls_cur_index];
g_troublesome_dlls[g_troublesome_dlls_cur_index] = NULL;
return true;
}
}
return false;
}
bool Initialize(bool force) {
#if defined(_WIN64)
// TODO(robertshield): Implement 64-bit support by providing 64-bit
// interceptors.
return false;
#endif
// Check to see that we found the functions we need in ntdll.
if (!InitializeInterceptImports())
return false;
// Check to see if this is a non-browser process, abort if so.
if (IsNonBrowserProcess())
return false;
// Check to see if a beacon is present, abort if so.
if (!force && !CreateBeacon())
return false;
// Don't try blacklisting on unsupported OS versions.
OSInfo os_info;
if (os_info.version() <= VERSION_PRE_XP_SP2)
return false;
// Pseudo-handle, no need to close.
HANDLE current_process = ::GetCurrentProcess();
// Tells the resolver to patch already patched functions.
const bool kRelaxed = true;
// Create a thunk via the appropriate ServiceResolver instance.
sandbox::ServiceResolverThunk* thunk;
#if defined(_WIN64)
// TODO(robertshield): Use the appropriate thunk for 64-bit support
// when said support is implemented.
#else
if (GetWOW64StatusForCurrentProcess() == WOW64_ENABLED) {
if (os_info.version() >= VERSION_WIN8)
thunk = new sandbox::Wow64W8ResolverThunk(current_process, kRelaxed);
else
thunk = new sandbox::Wow64ResolverThunk(current_process, kRelaxed);
} else if (os_info.version() >= VERSION_WIN8) {
thunk = new sandbox::Win8ResolverThunk(current_process, kRelaxed);
} else {
thunk = new sandbox::ServiceResolverThunk(current_process, kRelaxed);
}
#endif
#if defined(_WIN64) || (_MSC_VER >= 1700)
BYTE* thunk_storage = new BYTE[sizeof(sandbox::ThunkData)];
#else
BYTE* thunk_storage = reinterpret_cast<BYTE*>(&g_thunk_storage);
#endif
thunk->AllowLocalPatches();
// Get ntdll base, target name, interceptor address,
NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
reinterpret_cast<void*>(&__ImageBase),
"NtMapViewOfSection",
NULL,
&blacklist::BlNtMapViewOfSection,
thunk_storage,
sizeof(sandbox::ThunkData),
NULL);
delete thunk;
return NT_SUCCESS(ret);
}
} // namespace blacklist
<commit_msg>Fix Thunk Storage Allocation for blacklist.cc<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_elf/blacklist/blacklist.h"
#include <string.h>
#include "base/basictypes.h"
#include "chrome_elf/blacklist/blacklist_interceptions.h"
#include "sandbox/win/src/interception_internal.h"
#include "sandbox/win/src/internal_types.h"
#include "sandbox/win/src/sandbox_utils.h"
#include "sandbox/win/src/service_resolver.h"
// http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
extern "C" IMAGE_DOS_HEADER __ImageBase;
namespace blacklist{
const wchar_t* g_troublesome_dlls[kTroublesomeDllsMaxCount] = {};
int g_troublesome_dlls_cur_index = 0;
const wchar_t kRegistryBeaconPath[] = L"SOFTWARE\\Google\\Chrome\\BLBeacon";
} // namespace blacklist
// Allocate storage for thunks in a page of this module to save on doing
// an extra allocation at run time.
#pragma section(".crthunk",read,execute)
__declspec(allocate(".crthunk")) sandbox::ThunkData g_thunk_storage;
namespace {
enum Version {
VERSION_PRE_XP_SP2 = 0, // Not supported.
VERSION_XP_SP2,
VERSION_SERVER_2003, // Also includes XP Pro x64 and Server 2003 R2.
VERSION_VISTA, // Also includes Windows Server 2008.
VERSION_WIN7, // Also includes Windows Server 2008 R2.
VERSION_WIN8, // Also includes Windows Server 2012.
VERSION_WIN8_1,
VERSION_WIN_LAST, // Indicates error condition.
};
// Whether a process is running under WOW64 (the wrapper that allows 32-bit
// processes to run on 64-bit versions of Windows). This will return
// WOW64_DISABLED for both "32-bit Chrome on 32-bit Windows" and "64-bit
// Chrome on 64-bit Windows". WOW64_UNKNOWN means "an error occurred", e.g.
// the process does not have sufficient access rights to determine this.
enum WOW64Status {
WOW64_DISABLED,
WOW64_ENABLED,
WOW64_UNKNOWN,
};
WOW64Status GetWOW64StatusForCurrentProcess() {
typedef BOOL (WINAPI* IsWow64ProcessFunc)(HANDLE, PBOOL);
IsWow64ProcessFunc is_wow64_process = reinterpret_cast<IsWow64ProcessFunc>(
GetProcAddress(GetModuleHandle(L"kernel32.dll"), "IsWow64Process"));
if (!is_wow64_process)
return WOW64_DISABLED;
BOOL is_wow64 = FALSE;
if (!(*is_wow64_process)(GetCurrentProcess(), &is_wow64))
return WOW64_UNKNOWN;
return is_wow64 ? WOW64_ENABLED : WOW64_DISABLED;
}
class OSInfo {
public:
struct VersionNumber {
int major;
int minor;
int build;
};
struct ServicePack {
int major;
int minor;
};
OSInfo() {
OSVERSIONINFOEX version_info = { sizeof(version_info) };
GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&version_info));
version_number_.major = version_info.dwMajorVersion;
version_number_.minor = version_info.dwMinorVersion;
version_number_.build = version_info.dwBuildNumber;
if ((version_number_.major == 5) && (version_number_.minor > 0)) {
// Treat XP Pro x64, Home Server, and Server 2003 R2 as Server 2003.
version_ = (version_number_.minor == 1) ? VERSION_XP_SP2 :
VERSION_SERVER_2003;
if (version_ == VERSION_XP_SP2 && version_info.wServicePackMajor < 2)
version_ = VERSION_PRE_XP_SP2;
} else if (version_number_.major == 6) {
switch (version_number_.minor) {
case 0:
// Treat Windows Server 2008 the same as Windows Vista.
version_ = VERSION_VISTA;
break;
case 1:
// Treat Windows Server 2008 R2 the same as Windows 7.
version_ = VERSION_WIN7;
break;
case 2:
// Treat Windows Server 2012 the same as Windows 8.
version_ = VERSION_WIN8;
break;
default:
version_ = VERSION_WIN8_1;
break;
}
} else if (version_number_.major > 6) {
version_ = VERSION_WIN_LAST;
} else {
version_ = VERSION_PRE_XP_SP2;
}
service_pack_.major = version_info.wServicePackMajor;
service_pack_.minor = version_info.wServicePackMinor;
}
Version version() const { return version_; }
VersionNumber version_number() const { return version_number_; }
ServicePack service_pack() const { return service_pack_; }
private:
Version version_;
VersionNumber version_number_;
ServicePack service_pack_;
DISALLOW_COPY_AND_ASSIGN(OSInfo);
};
bool IsNonBrowserProcess() {
wchar_t* command_line = GetCommandLine();
return (command_line && wcsstr(command_line, L"--type"));
}
} // namespace
namespace blacklist {
bool CreateBeacon() {
HKEY beacon_key = NULL;
DWORD disposition = 0;
LONG result = ::RegCreateKeyEx(HKEY_CURRENT_USER,
kRegistryBeaconPath,
0,
NULL,
0,
KEY_WRITE,
NULL,
&beacon_key,
&disposition);
bool success = (result == ERROR_SUCCESS &&
disposition != REG_OPENED_EXISTING_KEY);
if (result == ERROR_SUCCESS)
::RegCloseKey(beacon_key);
return success;
}
bool ClearBeacon() {
LONG result = ::RegDeleteKey(HKEY_CURRENT_USER, kRegistryBeaconPath);
return (result == ERROR_SUCCESS);
}
bool AddDllToBlacklist(const wchar_t* dll_name) {
if (g_troublesome_dlls_cur_index >= kTroublesomeDllsMaxCount)
return false;
for (int i = 0; i < g_troublesome_dlls_cur_index; ++i) {
if (!wcscmp(g_troublesome_dlls[i], dll_name))
return true;
}
// Copy string to blacklist.
wchar_t* str_buffer = new wchar_t[wcslen(dll_name) + 1];
wcscpy(str_buffer, dll_name);
g_troublesome_dlls[g_troublesome_dlls_cur_index] = str_buffer;
g_troublesome_dlls_cur_index++;
return true;
}
bool RemoveDllFromBlacklist(const wchar_t* dll_name) {
for (int i = 0; i < g_troublesome_dlls_cur_index; ++i) {
if (!wcscmp(g_troublesome_dlls[i], dll_name)) {
// Found the thing to remove. Delete it then replace it with the last
// element.
g_troublesome_dlls_cur_index--;
delete[] g_troublesome_dlls[i];
g_troublesome_dlls[i] = g_troublesome_dlls[g_troublesome_dlls_cur_index];
g_troublesome_dlls[g_troublesome_dlls_cur_index] = NULL;
return true;
}
}
return false;
}
bool Initialize(bool force) {
#if defined(_WIN64)
// TODO(robertshield): Implement 64-bit support by providing 64-bit
// interceptors.
return false;
#endif
// Check to see that we found the functions we need in ntdll.
if (!InitializeInterceptImports())
return false;
// Check to see if this is a non-browser process, abort if so.
if (IsNonBrowserProcess())
return false;
// Check to see if a beacon is present, abort if so.
if (!force && !CreateBeacon())
return false;
// Don't try blacklisting on unsupported OS versions.
OSInfo os_info;
if (os_info.version() <= VERSION_PRE_XP_SP2)
return false;
// Pseudo-handle, no need to close.
HANDLE current_process = ::GetCurrentProcess();
// Tells the resolver to patch already patched functions.
const bool kRelaxed = true;
// Create a thunk via the appropriate ServiceResolver instance.
sandbox::ServiceResolverThunk* thunk;
#if defined(_WIN64)
// TODO(robertshield): Use the appropriate thunk for 64-bit support
// when said support is implemented.
#else
if (GetWOW64StatusForCurrentProcess() == WOW64_ENABLED) {
if (os_info.version() >= VERSION_WIN8)
thunk = new sandbox::Wow64W8ResolverThunk(current_process, kRelaxed);
else
thunk = new sandbox::Wow64ResolverThunk(current_process, kRelaxed);
} else if (os_info.version() >= VERSION_WIN8) {
thunk = new sandbox::Win8ResolverThunk(current_process, kRelaxed);
} else {
thunk = new sandbox::ServiceResolverThunk(current_process, kRelaxed);
}
#endif
BYTE* thunk_storage = reinterpret_cast<BYTE*>(&g_thunk_storage);
// Mark the thunk storage as readable and writeable, since we
// ready to write to it.
DWORD old_protect = 0;
if (!VirtualProtect(&g_thunk_storage,
sizeof(g_thunk_storage),
PAGE_EXECUTE_READWRITE,
&old_protect))
return false;
thunk->AllowLocalPatches();
// Get ntdll base, target name, interceptor address,
NTSTATUS ret = thunk->Setup(::GetModuleHandle(sandbox::kNtdllName),
reinterpret_cast<void*>(&__ImageBase),
"NtMapViewOfSection",
NULL,
&blacklist::BlNtMapViewOfSection,
thunk_storage,
sizeof(sandbox::ThunkData),
NULL);
delete thunk;
// Mark the thunk storage as executable and prevent any future writes to it.
BOOL page_executable = VirtualProtect(&g_thunk_storage,
sizeof(g_thunk_storage),
PAGE_EXECUTE_READ,
&old_protect);
return NT_SUCCESS(ret) && page_executable;
}
} // namespace blacklist
<|endoftext|>
|
<commit_before>//===- ARMLegalizerInfo.cpp --------------------------------------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the Machinelegalizer class for ARM.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//
#include "ARMLegalizerInfo.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/Target/TargetOpcodes.h"
using namespace llvm;
#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "You shouldn't build this"
#endif
ARMLegalizerInfo::ARMLegalizerInfo() {
using namespace TargetOpcode;
const LLT p0 = LLT::pointer(0, 32);
const LLT s1 = LLT::scalar(1);
const LLT s8 = LLT::scalar(8);
const LLT s16 = LLT::scalar(16);
const LLT s32 = LLT::scalar(32);
setAction({G_FRAME_INDEX, p0}, Legal);
for (auto Ty : {s1, s8, s16, s32})
setAction({G_LOAD, Ty}, Legal);
setAction({G_LOAD, 1, p0}, Legal);
for (auto Ty : {s1, s8, s16, s32})
setAction({G_ADD, Ty}, Legal);
for (auto Op : {G_SEXT, G_ZEXT}) {
setAction({Op, s32}, Legal);
for (auto Ty : {s1, s8, s16})
setAction({Op, 1, Ty}, Legal);
}
computeTables();
}
<commit_msg>[ARM][LegalizerInfo] Specify the type of the opcode.<commit_after>//===- ARMLegalizerInfo.cpp --------------------------------------*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements the targeting of the Machinelegalizer class for ARM.
/// \todo This should be generated by TableGen.
//===----------------------------------------------------------------------===//
#include "ARMLegalizerInfo.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Type.h"
#include "llvm/Target/TargetOpcodes.h"
using namespace llvm;
#ifndef LLVM_BUILD_GLOBAL_ISEL
#error "You shouldn't build this"
#endif
ARMLegalizerInfo::ARMLegalizerInfo() {
using namespace TargetOpcode;
const LLT p0 = LLT::pointer(0, 32);
const LLT s1 = LLT::scalar(1);
const LLT s8 = LLT::scalar(8);
const LLT s16 = LLT::scalar(16);
const LLT s32 = LLT::scalar(32);
setAction({G_FRAME_INDEX, p0}, Legal);
for (auto Ty : {s1, s8, s16, s32})
setAction({G_LOAD, Ty}, Legal);
setAction({G_LOAD, 1, p0}, Legal);
for (auto Ty : {s1, s8, s16, s32})
setAction({G_ADD, Ty}, Legal);
for (unsigned Op : {G_SEXT, G_ZEXT}) {
setAction({Op, s32}, Legal);
for (auto Ty : {s1, s8, s16})
setAction({Op, 1, Ty}, Legal);
}
computeTables();
}
<|endoftext|>
|
<commit_before>#include "../../testing/testing.hpp"
#include "../trie.hpp"
#include "../trie_builder.hpp"
#include "../trie_reader.hpp"
#include "../byte_stream.hpp"
#include "../write_to_sink.hpp"
#include "../../base/logging.hpp"
#include "../../std/algorithm.hpp"
#include "../../std/scoped_ptr.hpp"
#include "../../std/string.hpp"
#include "../../std/vector.hpp"
#include <boost/utility/binary.hpp>
namespace
{
struct ChildNodeInfo
{
bool m_isLeaf;
uint32_t m_size;
vector<uint32_t> m_edge;
string m_edgeValue;
ChildNodeInfo(bool isLeaf, uint32_t size, char const * edge, char const * edgeValue)
: m_isLeaf(isLeaf), m_size(size), m_edgeValue(edgeValue)
{
while (*edge)
m_edge.push_back(*edge++);
}
uint32_t Size() const { return m_size; }
bool IsLeaf() const { return m_isLeaf; }
uint32_t const * GetEdge() const { return &m_edge[0]; }
uint32_t GetEdgeSize() const { return m_edge.size(); }
void const * GetEdgeValue() const { return m_edgeValue.data(); }
uint32_t GetEdgeValueSize() const { return m_edgeValue.size(); }
};
struct KeyValuePair
{
buffer_vector<trie::TrieChar, 8> m_key;
uint32_t m_value;
KeyValuePair() {}
template <class StringT>
KeyValuePair(StringT const & key, int value)
: m_key(key.begin(), key.end()), m_value(value)
{}
uint32_t GetKeySize() const { return m_key.size(); }
trie::TrieChar const * GetKeyData() const { return m_key.data(); }
template <class TCont> void SerializeValue(TCont & cont) const
{
cont.resize(4);
memcpy(cont.data(), &m_value, 4);
}
bool operator == (KeyValuePair const & p) const
{
return (m_key == p.m_key && m_value == p.m_value);
}
bool operator < (KeyValuePair const & p) const
{
return ((m_key != p.m_key) ? m_key < p.m_key : m_value < p.m_value);
}
void Swap(KeyValuePair & r)
{
m_key.swap(r.m_key);
swap(m_value, r.m_value);
}
};
string DebugPrint(KeyValuePair const & p)
{
string keyS = ::DebugPrint(p.m_key);
ostringstream out;
out << "KVP(" << keyS << ", " << p.m_value << ")";
return out.str();
}
struct KeyValuePairBackInserter
{
vector<KeyValuePair> m_v;
template <class StringT>
void operator() (StringT const & s,
trie::reader::FixedSizeValueReader<4>::ValueType const & rawValue)
{
uint32_t value;
memcpy(&value, &rawValue, 4);
m_v.push_back(KeyValuePair(s, value));
}
};
struct MaxValueCalc
{
typedef uint8_t ValueType;
ValueType operator() (void const * p, uint32_t size) const
{
ASSERT_EQUAL(size, 4, ());
uint32_t value;
memcpy(&value, p, 4);
ASSERT_LESS(value, 256, ());
return static_cast<uint8_t>(value);
}
};
} // unnamed namespace
#define ZENC bits::ZigZagEncode
#define MKSC(x) static_cast<signed char>(x)
UNIT_TEST(TrieBuilder_WriteNode_Smoke)
{
vector<uint8_t> serial;
PushBackByteSink<vector<uint8_t> > sink(serial);
ChildNodeInfo children[] =
{
ChildNodeInfo(true, 1, "1A", "i1"),
ChildNodeInfo(false, 2, "B", "ii2"),
ChildNodeInfo(false, 3, "zz", ""),
ChildNodeInfo(true, 4,
"abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij", "i4"),
ChildNodeInfo(true, 5, "a", "5z")
};
trie::builder::WriteNode(sink, 0, 3, "123", 3,
&children[0], &children[0] + ARRAY_SIZE(children));
uint8_t const expected [] =
{
BOOST_BINARY(11000101), // Header: [0b11] [0b000101]
3, // Number of values
'1', '2', '3', // Values
BOOST_BINARY(10000001), // Child 1: header: [+leaf] [-supershort] [2 symbols]
static_cast<uint8_t>(ZENC(MKSC('1'))), static_cast<uint8_t>(ZENC(MKSC('A') - MKSC('1'))), // Child 1: edge
'i', '1', // Child 1: intermediate data
1, // Child 1: size
static_cast<uint8_t>(64 | ZENC(MKSC('B') - MKSC('1'))), // Child 2: header: [-leaf] [+supershort]
'i', 'i', '2', // Child 2: intermediate data
2, // Child 2: size
BOOST_BINARY(00000001), // Child 3: header: [-leaf] [-supershort] [2 symbols]
static_cast<uint8_t>(ZENC(MKSC('z') - MKSC('B'))), 0, // Child 3: edge
3, // Child 3: size
BOOST_BINARY(10111111), // Child 4: header: [+leaf] [-supershort] [>= 63 symbols]
69, // Child 4: edgeSize - 1
static_cast<uint8_t>(ZENC(MKSC('a') - MKSC('z'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
static_cast<uint8_t>(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
static_cast<uint8_t>(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
static_cast<uint8_t>(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
static_cast<uint8_t>(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
static_cast<uint8_t>(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
static_cast<uint8_t>(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
'i', '4', // Child 4: intermediate data
4, // Child 4: size
static_cast<uint8_t>(BOOST_BINARY(11000000) | ZENC(0)), // Child 5: header: [+leaf] [+supershort]
'5', 'z' // Child 5: intermediate data
};
TEST_EQUAL(serial, vector<uint8_t>(&expected[0], &expected[0] + ARRAY_SIZE(expected)), ());
}
UNIT_TEST(TrieBuilder_Build)
{
int const base = 3;
int const maxLen = 3;
vector<string> possibleStrings(1, string());
for (int len = 1; len <= maxLen; ++len)
{
for (int i = 0, p = static_cast<int>(pow((double) base, len)); i < p; ++i)
{
string s(len, 'A');
int t = i;
for (int l = len - 1; l >= 0; --l, t /= base)
s[l] += (t % base);
possibleStrings.push_back(s);
}
}
sort(possibleStrings.begin(), possibleStrings.end());
// LOG(LINFO, (possibleStrings));
int const count = static_cast<int>(possibleStrings.size());
for (int i0 = -1; i0 < count; ++i0)
for (int i1 = i0; i1 < count; ++i1)
for (int i2 = i1; i2 < count; ++i2)
{
vector<KeyValuePair> v;
if (i0 >= 0) v.push_back(KeyValuePair(possibleStrings[i0], i0));
if (i1 >= 0) v.push_back(KeyValuePair(possibleStrings[i1], i1 + 10));
if (i2 >= 0) v.push_back(KeyValuePair(possibleStrings[i2], i2 + 100));
vector<string> vs;
for (size_t i = 0; i < v.size(); ++i)
vs.push_back(string(v[i].m_key.begin(), v[i].m_key.end()));
vector<uint8_t> serial;
PushBackByteSink<vector<uint8_t> > sink(serial);
trie::Build(sink, v.begin(), v.end(), trie::builder::MaxValueEdgeBuilder<MaxValueCalc>());
reverse(serial.begin(), serial.end());
// LOG(LINFO, (serial.size(), vs));
MemReader memReader = MemReader(&serial[0], serial.size());
typedef trie::Iterator<
trie::reader::FixedSizeValueReader<4>::ValueType,
trie::reader::FixedSizeValueReader<1>::ValueType
> IteratorType;
scoped_ptr<IteratorType> root(trie::reader::ReadTrie(memReader,
trie::reader::FixedSizeValueReader<4>(),
trie::reader::FixedSizeValueReader<1>()));
vector<KeyValuePair> res;
KeyValuePairBackInserter f;
trie::ForEachRef(*root, f, vector<trie::TrieChar>());
sort(f.m_v.begin(), f.m_v.end());
TEST_EQUAL(v, f.m_v, ());
uint32_t expectedMaxEdgeValue = 0;
for (size_t i = 0; i < v.size(); ++i)
if (!v[i].m_key.empty())
expectedMaxEdgeValue = max(expectedMaxEdgeValue, v[i].m_value);
uint32_t maxEdgeValue = 0;
for (uint32_t i = 0; i < root->m_edge.size(); ++i)
maxEdgeValue = max(maxEdgeValue, static_cast<uint32_t>(root->m_edge[i].m_value.m_data[0]));
TEST_EQUAL(maxEdgeValue, expectedMaxEdgeValue, (v, f.m_v));
}
}
<commit_msg>[tests] added MKUC macro<commit_after>#include "../../testing/testing.hpp"
#include "../trie.hpp"
#include "../trie_builder.hpp"
#include "../trie_reader.hpp"
#include "../byte_stream.hpp"
#include "../write_to_sink.hpp"
#include "../../base/logging.hpp"
#include "../../std/algorithm.hpp"
#include "../../std/scoped_ptr.hpp"
#include "../../std/string.hpp"
#include "../../std/vector.hpp"
#include <boost/utility/binary.hpp>
namespace
{
struct ChildNodeInfo
{
bool m_isLeaf;
uint32_t m_size;
vector<uint32_t> m_edge;
string m_edgeValue;
ChildNodeInfo(bool isLeaf, uint32_t size, char const * edge, char const * edgeValue)
: m_isLeaf(isLeaf), m_size(size), m_edgeValue(edgeValue)
{
while (*edge)
m_edge.push_back(*edge++);
}
uint32_t Size() const { return m_size; }
bool IsLeaf() const { return m_isLeaf; }
uint32_t const * GetEdge() const { return &m_edge[0]; }
uint32_t GetEdgeSize() const { return m_edge.size(); }
void const * GetEdgeValue() const { return m_edgeValue.data(); }
uint32_t GetEdgeValueSize() const { return m_edgeValue.size(); }
};
struct KeyValuePair
{
buffer_vector<trie::TrieChar, 8> m_key;
uint32_t m_value;
KeyValuePair() {}
template <class StringT>
KeyValuePair(StringT const & key, int value)
: m_key(key.begin(), key.end()), m_value(value)
{}
uint32_t GetKeySize() const { return m_key.size(); }
trie::TrieChar const * GetKeyData() const { return m_key.data(); }
template <class TCont> void SerializeValue(TCont & cont) const
{
cont.resize(4);
memcpy(cont.data(), &m_value, 4);
}
bool operator == (KeyValuePair const & p) const
{
return (m_key == p.m_key && m_value == p.m_value);
}
bool operator < (KeyValuePair const & p) const
{
return ((m_key != p.m_key) ? m_key < p.m_key : m_value < p.m_value);
}
void Swap(KeyValuePair & r)
{
m_key.swap(r.m_key);
swap(m_value, r.m_value);
}
};
string DebugPrint(KeyValuePair const & p)
{
string keyS = ::DebugPrint(p.m_key);
ostringstream out;
out << "KVP(" << keyS << ", " << p.m_value << ")";
return out.str();
}
struct KeyValuePairBackInserter
{
vector<KeyValuePair> m_v;
template <class StringT>
void operator() (StringT const & s,
trie::reader::FixedSizeValueReader<4>::ValueType const & rawValue)
{
uint32_t value;
memcpy(&value, &rawValue, 4);
m_v.push_back(KeyValuePair(s, value));
}
};
struct MaxValueCalc
{
typedef uint8_t ValueType;
ValueType operator() (void const * p, uint32_t size) const
{
ASSERT_EQUAL(size, 4, ());
uint32_t value;
memcpy(&value, p, 4);
ASSERT_LESS(value, 256, ());
return static_cast<uint8_t>(value);
}
};
} // unnamed namespace
#define ZENC bits::ZigZagEncode
#define MKSC(x) static_cast<signed char>(x)
#define MKUC(x) static_cast<uint8_t>(x)
UNIT_TEST(TrieBuilder_WriteNode_Smoke)
{
vector<uint8_t> serial;
PushBackByteSink<vector<uint8_t> > sink(serial);
ChildNodeInfo children[] =
{
ChildNodeInfo(true, 1, "1A", "i1"),
ChildNodeInfo(false, 2, "B", "ii2"),
ChildNodeInfo(false, 3, "zz", ""),
ChildNodeInfo(true, 4,
"abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghij", "i4"),
ChildNodeInfo(true, 5, "a", "5z")
};
trie::builder::WriteNode(sink, 0, 3, "123", 3,
&children[0], &children[0] + ARRAY_SIZE(children));
uint8_t const expected [] =
{
BOOST_BINARY(11000101), // Header: [0b11] [0b000101]
3, // Number of values
'1', '2', '3', // Values
BOOST_BINARY(10000001), // Child 1: header: [+leaf] [-supershort] [2 symbols]
MKUC(ZENC(MKSC('1'))), MKUC(ZENC(MKSC('A') - MKSC('1'))), // Child 1: edge
'i', '1', // Child 1: intermediate data
1, // Child 1: size
MKUC(64 | ZENC(MKSC('B') - MKSC('1'))), // Child 2: header: [-leaf] [+supershort]
'i', 'i', '2', // Child 2: intermediate data
2, // Child 2: size
BOOST_BINARY(00000001), // Child 3: header: [-leaf] [-supershort] [2 symbols]
MKUC(ZENC(MKSC('z') - MKSC('B'))), 0, // Child 3: edge
3, // Child 3: size
BOOST_BINARY(10111111), // Child 4: header: [+leaf] [-supershort] [>= 63 symbols]
69, // Child 4: edgeSize - 1
MKUC(ZENC(MKSC('a') - MKSC('z'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
MKUC(ZENC(MKSC('a') - MKSC('j'))), 2,2,2,2,2,2,2,2,2, // Child 4: edge
'i', '4', // Child 4: intermediate data
4, // Child 4: size
MKUC(BOOST_BINARY(11000000) | ZENC(0)), // Child 5: header: [+leaf] [+supershort]
'5', 'z' // Child 5: intermediate data
};
TEST_EQUAL(serial, vector<uint8_t>(&expected[0], &expected[0] + ARRAY_SIZE(expected)), ());
}
UNIT_TEST(TrieBuilder_Build)
{
int const base = 3;
int const maxLen = 3;
vector<string> possibleStrings(1, string());
for (int len = 1; len <= maxLen; ++len)
{
for (int i = 0, p = static_cast<int>(pow((double) base, len)); i < p; ++i)
{
string s(len, 'A');
int t = i;
for (int l = len - 1; l >= 0; --l, t /= base)
s[l] += (t % base);
possibleStrings.push_back(s);
}
}
sort(possibleStrings.begin(), possibleStrings.end());
// LOG(LINFO, (possibleStrings));
int const count = static_cast<int>(possibleStrings.size());
for (int i0 = -1; i0 < count; ++i0)
for (int i1 = i0; i1 < count; ++i1)
for (int i2 = i1; i2 < count; ++i2)
{
vector<KeyValuePair> v;
if (i0 >= 0) v.push_back(KeyValuePair(possibleStrings[i0], i0));
if (i1 >= 0) v.push_back(KeyValuePair(possibleStrings[i1], i1 + 10));
if (i2 >= 0) v.push_back(KeyValuePair(possibleStrings[i2], i2 + 100));
vector<string> vs;
for (size_t i = 0; i < v.size(); ++i)
vs.push_back(string(v[i].m_key.begin(), v[i].m_key.end()));
vector<uint8_t> serial;
PushBackByteSink<vector<uint8_t> > sink(serial);
trie::Build(sink, v.begin(), v.end(), trie::builder::MaxValueEdgeBuilder<MaxValueCalc>());
reverse(serial.begin(), serial.end());
// LOG(LINFO, (serial.size(), vs));
MemReader memReader = MemReader(&serial[0], serial.size());
typedef trie::Iterator<
trie::reader::FixedSizeValueReader<4>::ValueType,
trie::reader::FixedSizeValueReader<1>::ValueType
> IteratorType;
scoped_ptr<IteratorType> root(trie::reader::ReadTrie(memReader,
trie::reader::FixedSizeValueReader<4>(),
trie::reader::FixedSizeValueReader<1>()));
vector<KeyValuePair> res;
KeyValuePairBackInserter f;
trie::ForEachRef(*root, f, vector<trie::TrieChar>());
sort(f.m_v.begin(), f.m_v.end());
TEST_EQUAL(v, f.m_v, ());
uint32_t expectedMaxEdgeValue = 0;
for (size_t i = 0; i < v.size(); ++i)
if (!v[i].m_key.empty())
expectedMaxEdgeValue = max(expectedMaxEdgeValue, v[i].m_value);
uint32_t maxEdgeValue = 0;
for (uint32_t i = 0; i < root->m_edge.size(); ++i)
maxEdgeValue = max(maxEdgeValue, static_cast<uint32_t>(root->m_edge[i].m_value.m_data[0]));
TEST_EQUAL(maxEdgeValue, expectedMaxEdgeValue, (v, f.m_v));
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012, 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 the <ORGANIZATION> 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.
*/
// Author: E. Gil Jones
#include <moveit_manipulation_visualization/place_generator_dummy.h>
#include <geometric_shapes/shape_operations.h>
namespace moveit_manipulation_visualization {
bool PlaceGeneratorDummy::generatePlaceLocations(const planning_scene::PlanningSceneConstPtr& planning_scene,
const std::string& object,
const std::string& support,
std::vector<geometry_msgs::PoseStamped>& place_locations)
{
place_locations.clear();
moveit_msgs::CollisionObject sup;
if(!planning_scene->getCollisionObjectMsg(support,
sup)) {
ROS_WARN_STREAM("Don't appear to have object " << support << " in planning scene for place support");
return false;
}
std::vector<const planning_models::KinematicState::AttachedBody*> ab;
planning_scene->getCurrentState().getAttachedBodies(ab);
if(ab.size() == 0) {
ROS_WARN_STREAM("No attached bodies associated with current state of planning scene. Can't place");
return false;
}
moveit_msgs::Shape attached_shape;
bool found = false;
for(unsigned int i = 0; i < ab.size(); i++) {
if(ab[i]->getName() == object) {
shapes::constructMsgFromShape(ab[i]->getShapes()[0], attached_shape);
found = true;
break;
}
}
if(!found) {
ROS_WARN_STREAM("Don't appear to have object " << object << " in planning scene for place");
}
Eigen::Affine3d sup_pose;
planning_models::poseFromMsg(sup.poses[0], sup_pose);
if(sup.shapes[0].dimensions.size() != 3) {
ROS_WARN_STREAM("Dummy generator can only deal with support surface boxes");
return false;
}
double xex, yex, zex;
shapes::getShapeExtents(attached_shape, xex, yex, zex);
double l = sup.shapes[0].dimensions[0]-xex;
double w = sup.shapes[0].dimensions[1]-yex;
double d = sup.shapes[0].dimensions[2]/2.0;//+zex/2.0;
double spacing = .1;
unsigned int lnum = floor(l/spacing);
unsigned int wnum = floor(w/spacing);
l = ((lnum*1.0)*spacing);
w = ((wnum*1.0)*spacing);
std::vector<double> angles;
angles.push_back(0);
angles.push_back(M_PI/4.0);
angles.push_back(-M_PI/4.0);
angles.push_back(M_PI/2.0);
angles.push_back(-M_PI/2.0);
angles.push_back(-M_PI);
angles.push_back(M_PI);
unsigned int total_place_locations = lnum*wnum*angles.size();
if(total_place_locations == 0) {
ROS_WARN_STREAM("Surface too small for placing");
return false;
}
std::vector<unsigned int> random_numbers(total_place_locations);
for(unsigned int i = 0; i < total_place_locations; i++) {
random_numbers[i] = i;
}
//random_shuffle(random_numbers.begin(), random_numbers.end());
place_locations.resize(total_place_locations);
unsigned int cur_ind = 0;
for(unsigned int i = 0; i < lnum; i++) {
for(unsigned int j = 0; j < wnum; j++) {
for(unsigned int k = 0; k < angles.size(); k++, cur_ind++) {
geometry_msgs::PoseStamped place_pose;
place_pose.pose = sup.poses[0];
place_pose.header.frame_id = planning_scene->getPlanningFrame();
place_pose.pose.position.x += -(l/2.0)+((i*1.0)*spacing);
place_pose.pose.position.y += -(w/2.0)+((j*1.0)*spacing);
place_pose.pose.position.z += d;
Eigen::Affine3d cur;
planning_models::poseFromMsg(place_pose.pose, cur);
Eigen::Affine3d trans(Eigen::AngleAxisd(angles[k], Eigen::Vector3d::UnitZ()));
Eigen::Affine3d conv = cur*trans;
planning_models::msgFromPose(conv, place_pose.pose);
ROS_DEBUG_STREAM("Place location " << i << " " << j << " "
<< place_pose.pose.position.x << " "
<< place_pose.pose.position.y << " "
<< place_pose.pose.position.z);
place_locations[random_numbers[cur_ind]] = place_pose;
}
}
}
return true;
}
}
<commit_msg>Updating for shape API<commit_after>/*
* Copyright (c) 2012, 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 the <ORGANIZATION> 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.
*/
// Author: E. Gil Jones
#include <moveit_manipulation_visualization/place_generator_dummy.h>
#include <geometric_shapes/shape_operations.h>
namespace moveit_manipulation_visualization {
bool PlaceGeneratorDummy::generatePlaceLocations(const planning_scene::PlanningSceneConstPtr& planning_scene,
const std::string& object,
const std::string& support,
std::vector<geometry_msgs::PoseStamped>& place_locations)
{
place_locations.clear();
moveit_msgs::CollisionObject sup;
if(!planning_scene->getCollisionObjectMsg(support,
sup)) {
ROS_WARN_STREAM("Don't appear to have object " << support << " in planning scene for place support");
return false;
}
std::vector<const planning_models::KinematicState::AttachedBody*> ab;
planning_scene->getCurrentState().getAttachedBodies(ab);
if(ab.size() == 0) {
ROS_WARN_STREAM("No attached bodies associated with current state of planning scene. Can't place");
return false;
}
moveit_msgs::Shape attached_shape;
bool found = false;
for(unsigned int i = 0; i < ab.size(); i++) {
if(ab[i]->getName() == object) {
shapes::constructMsgFromShape(ab[i]->getShapes()[0].get(), attached_shape);
found = true;
break;
}
}
if(!found) {
ROS_WARN_STREAM("Don't appear to have object " << object << " in planning scene for place");
}
Eigen::Affine3d sup_pose;
planning_models::poseFromMsg(sup.poses[0], sup_pose);
if(sup.shapes[0].dimensions.size() != 3) {
ROS_WARN_STREAM("Dummy generator can only deal with support surface boxes");
return false;
}
double xex, yex, zex;
shapes::getShapeExtents(attached_shape, xex, yex, zex);
double l = sup.shapes[0].dimensions[0]-xex;
double w = sup.shapes[0].dimensions[1]-yex;
double d = sup.shapes[0].dimensions[2]/2.0;//+zex/2.0;
double spacing = .1;
unsigned int lnum = floor(l/spacing);
unsigned int wnum = floor(w/spacing);
l = ((lnum*1.0)*spacing);
w = ((wnum*1.0)*spacing);
std::vector<double> angles;
angles.push_back(0);
angles.push_back(M_PI/4.0);
angles.push_back(-M_PI/4.0);
angles.push_back(M_PI/2.0);
angles.push_back(-M_PI/2.0);
angles.push_back(-M_PI);
angles.push_back(M_PI);
unsigned int total_place_locations = lnum*wnum*angles.size();
if(total_place_locations == 0) {
ROS_WARN_STREAM("Surface too small for placing");
return false;
}
std::vector<unsigned int> random_numbers(total_place_locations);
for(unsigned int i = 0; i < total_place_locations; i++) {
random_numbers[i] = i;
}
//random_shuffle(random_numbers.begin(), random_numbers.end());
place_locations.resize(total_place_locations);
unsigned int cur_ind = 0;
for(unsigned int i = 0; i < lnum; i++) {
for(unsigned int j = 0; j < wnum; j++) {
for(unsigned int k = 0; k < angles.size(); k++, cur_ind++) {
geometry_msgs::PoseStamped place_pose;
place_pose.pose = sup.poses[0];
place_pose.header.frame_id = planning_scene->getPlanningFrame();
place_pose.pose.position.x += -(l/2.0)+((i*1.0)*spacing);
place_pose.pose.position.y += -(w/2.0)+((j*1.0)*spacing);
place_pose.pose.position.z += d;
Eigen::Affine3d cur;
planning_models::poseFromMsg(place_pose.pose, cur);
Eigen::Affine3d trans(Eigen::AngleAxisd(angles[k], Eigen::Vector3d::UnitZ()));
Eigen::Affine3d conv = cur*trans;
planning_models::msgFromPose(conv, place_pose.pose);
ROS_DEBUG_STREAM("Place location " << i << " " << j << " "
<< place_pose.pose.position.x << " "
<< place_pose.pose.position.y << " "
<< place_pose.pose.position.z);
place_locations[random_numbers[cur_ind]] = place_pose;
}
}
}
return true;
}
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////////////////////
#include "timer_queue_t.h"
#include "base_guard.h"
#include <iostream>
BASE_NAMESPACE_BEGIN_DECL
#define UNINT32_MAX 4294967296
#define SELECT_DELAY 5
/////////////////////////////////////////////////////////////////////////////////////////
template<class HANDLER, class FUNCTOR, class LOCK>
CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::CTimerQueue_T(FUNCTOR* functor, size_t heap_size /* = 10240 */)
{
heap_size_ = 0;
alloc_heap(heap_size);
used_num_ = 0;
cur_heap_pos_ = 0;
//ʼʱ
start_time_ = CBaseTimeValue::get_time_value();
prev_time_ = start_time_;
functor_ = functor;
for(uint8_t index = 0; index < RINGS_SIZE; index ++)
{
rings_[index].set_ring_id(index);
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::~CTimerQueue_T()
{
clear();
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::clear()
{
BASE_GUARD(LOCK, cf_mon, mutex_);
for(uint32_t i = 0; i < heap_size_; i ++)
{
if(heap_[i] != NULL)
{
node_pool_.push_obj(heap_[i]);
heap_[i] = NULL;
freeTimers_.push_back(i);
}
}
used_num_ = 0;
cur_heap_pos_ = 0;
}
template<class HANDLER, class FUNCTOR, class LOCK>
bool CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::full() const
{
return used_num_ >= heap_size_ - 1;
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::alloc_heap(size_t size)
{
heap_.resize(size + heap_size_);
for(uint32_t i = 0; i < size; i ++)
{
heap_[heap_size_] = NULL;
if(heap_size_ > 0)
freeTimers_.push_back(heap_size_);
heap_size_ ++;
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::get_free_node()
{
if(full())
{
alloc_heap(heap_size_ + 1);
}
uint32_t ret = freeTimers_.front();
freeTimers_.pop_front();
if(heap_[ret] != NULL)
assert(0);
return ret;
}
template<class HANDLER, class FUNCTOR, class LOCK>
FUNCTOR &CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::upcall_functor()
{
return *(this->functor_);
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::schedule(HANDLER handler,
const void *act,
uint32_t delay,
uint32_t interval)
{
BASE_GUARD_RETURN(LOCK, cf_mon, mutex_, 0);
BaseTimerNode_T<HANDLER>* timer_obj = node_pool_.pop_obj();
if(timer_obj != NULL)
{
uint32_t timer_id = get_free_node();
CBaseTimeValue cur_timer = CBaseTimeValue::get_time_value();
uint64_t distance = delay; //ֱԵǰʱΪ꣬һɨ20MS
if(cur_timer > start_time_)
distance = (cur_timer.msec() - start_time_.msec() + delay);// SELECT_DELAY;
distance = distance % (UNINT32_MAX);
timer_obj->set(handler, act, (uint32_t)(core_max(distance, 1)), interval, timer_id);
heap_[timer_id] = timer_obj;
used_num_ ++;
insert_node(timer_obj);
upcall_functor().registration(timer_obj->get_handler(), timer_id);
return timer_id;
}
return 0;
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::cancel_timer(uint32_t timer_id, const void **act)
{
BASE_GUARD(LOCK, cf_mon, mutex_);
if(timer_id < heap_size_ && heap_[timer_id] != NULL)
{
BaseTimerNode_T<HANDLER>* timer_obj = heap_[timer_id];
delete_node(timer_obj);
heap_[timer_id] = NULL;
if(used_num_ > 0)
used_num_ --;
freeTimers_.push_back(timer_id);
*act = timer_obj->get_act();
upcall_functor().cancel_timer(timer_obj->get_handler(), timer_id);
node_pool_.push_obj(timer_obj);
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::reset_timer(uint32_t timer_id, uint32_t delay, uint32_t interval /* = 0 */)
{
BASE_GUARD_RETURN(LOCK, cf_mon, mutex_, 0);
if(timer_id < heap_size_ && heap_[timer_id] != NULL)
{
BaseTimerNode_T<HANDLER>* timer_obj = heap_[timer_id];
delete_node(timer_obj);
timer_obj->set_internal(interval);
CBaseTimeValue cur_timer = CBaseTimeValue::get_time_value();
uint64_t distance = delay; // SELECT_DELAY; //ֱԵǰʱΪ꣬һɨ20MS
if(cur_timer > start_time_)
distance = (cur_timer.msec() - start_time_.msec() + delay); // SELECT_DELAY;
distance = distance % (UNINT32_MAX);
timer_obj->set_time_stamp(core_max(distance, 1));
insert_node(timer_obj);
return timer_id;
}
else
{
return 0;
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::expire()
{
BASE_GUARD_RETURN(LOCK, cf_mon, mutex_, 0);
uint32_t ret = SELECT_DELAY; //Ĭ20MS
CBaseTimeValue cur_timer = CBaseTimeValue::get_time_value();
if(cur_timer > prev_time_)
{
uint32_t scale = static_cast<uint32_t>((cur_timer.msec() - prev_time_.msec()));// SELECT_DELAY);
if(scale > 0)
{
ret = revolver(scale);
prev_time_ = cur_timer;
}
}
return ret;
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::revolver(uint32_t scale)
{
//std::cout << "pos, first = " << rings_[0].get_pos() << ", second = " << rings_[1].get_pos()
// << ", third = " << rings_[2].get_pos() << ", fourth = " << rings_[3].get_pos() <<std::endl;
uint32_t ret = SELECT_DELAY;
uint8_t index = 0;
uint32_t rewind_scale = scale;
while(rewind_scale > 0)
{
index = 0;
if(rings_[index].cycle(rewind_scale, this)) //ɨһ
{
index ++;
uint32_t sc = 1;
while(rings_[index].cycle(sc, this))//ɨһ̶ֻ֣ǰƽ1
{
sc = 1;
index ++;
if(index >= RINGS_SIZE)
{
start_time_ = CBaseTimeValue::get_time_value();
break;
}
}
}
}
return ret;
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::ring_event(uint8_t ring_id, uint32_t timer_id)
{
if(heap_[timer_id] == NULL)
return;
BaseTimerNode_T<HANDLER>* timer_obj = heap_[timer_id];
if(ring_id == 0)
{
//ʱ֪ͨ
BaseTimerDispathInfo_T<HANDLER> info;
if(timer_obj != NULL)
{
timer_obj->get_dispatch_info(info);
this->dispatch_info(info, timer_id);
node_pool_.push_obj(timer_obj);
}
heap_[timer_id] = NULL;
if(used_num_ > 0)
used_num_ --;
freeTimers_.push_back(timer_id);
}
else if(ring_id < RINGS_SIZE)
{
//ƶRINGλã磬ڶӵijԪжʱӳ䵽һϽ·ֲ
insert_node(timer_obj);
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::insert_node(BaseTimerNode_T<HANDLER>* node)
{
uint32_t timer_id = node->get_timer_id();
uint8_t poss[RINGS_SIZE] = {0};
node->get_revolver_pos(poss[RINGS_SIZE - 1], poss[RINGS_SIZE - 2], poss[RINGS_SIZE - 3], poss[RINGS_SIZE - 4]);
//cout << "timer id = "<< timer_id << ", first = " << (uint16_t)poss[RINGS_SIZE - 4] << ",second = " << (uint16_t)poss[RINGS_SIZE - 3]
//<< ",third = " << (uint16_t)poss[RINGS_SIZE - 2] <<", fouth = " << (uint16_t)poss[RINGS_SIZE - 1] <<endl;
uint8_t index = RINGS_SIZE - 1;
while(!rings_[index].add_element(poss[index], timer_id))
{
if(index == 0)
break ;
index --;
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::delete_node(BaseTimerNode_T<HANDLER>* node)
{
uint32_t timer_id = node->get_timer_id();
uint8_t poss[RINGS_SIZE] = {0};
node->get_revolver_pos(poss[RINGS_SIZE - 1], poss[RINGS_SIZE - 2], poss[RINGS_SIZE - 3], poss[RINGS_SIZE - 4]);
for(uint8_t index = 0; index < RINGS_SIZE; index ++) //ÿϽɾ
{
rings_[index].delete_element(poss[index], timer_id);
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::dispatch_info(BaseTimerDispathInfo_T<HANDLER>& info, uint32_t timer_id)
{
upcall_functor().timer_out(info.handler_, info.act_, info.recurring_, timer_id);
}
#if _DEBUG
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::set_ring_id()
{
rings_[1].set_pos(255);
rings_[2].set_pos(0);
rings_[3].set_pos(0);
}
#endif
BASE_NAMESPACE_END_DECL
/////////////////////////////////////////////////////////////////////////////////////////
<commit_msg>修改epoll轮询时间<commit_after>/////////////////////////////////////////////////////////////////////////////////////////
#include "timer_queue_t.h"
#include "base_guard.h"
#include <iostream>
BASE_NAMESPACE_BEGIN_DECL
#define UNINT32_MAX 4294967296
#define SELECT_DELAY 1
/////////////////////////////////////////////////////////////////////////////////////////
template<class HANDLER, class FUNCTOR, class LOCK>
CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::CTimerQueue_T(FUNCTOR* functor, size_t heap_size /* = 10240 */)
{
heap_size_ = 0;
alloc_heap(heap_size);
used_num_ = 0;
cur_heap_pos_ = 0;
//ʼʱ
start_time_ = CBaseTimeValue::get_time_value();
prev_time_ = start_time_;
functor_ = functor;
for(uint8_t index = 0; index < RINGS_SIZE; index ++)
{
rings_[index].set_ring_id(index);
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::~CTimerQueue_T()
{
clear();
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::clear()
{
BASE_GUARD(LOCK, cf_mon, mutex_);
for(uint32_t i = 0; i < heap_size_; i ++)
{
if(heap_[i] != NULL)
{
node_pool_.push_obj(heap_[i]);
heap_[i] = NULL;
freeTimers_.push_back(i);
}
}
used_num_ = 0;
cur_heap_pos_ = 0;
}
template<class HANDLER, class FUNCTOR, class LOCK>
bool CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::full() const
{
return used_num_ >= heap_size_ - 1;
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::alloc_heap(size_t size)
{
heap_.resize(size + heap_size_);
for(uint32_t i = 0; i < size; i ++)
{
heap_[heap_size_] = NULL;
if(heap_size_ > 0)
freeTimers_.push_back(heap_size_);
heap_size_ ++;
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::get_free_node()
{
if(full())
{
alloc_heap(heap_size_ + 1);
}
uint32_t ret = freeTimers_.front();
freeTimers_.pop_front();
if(heap_[ret] != NULL)
assert(0);
return ret;
}
template<class HANDLER, class FUNCTOR, class LOCK>
FUNCTOR &CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::upcall_functor()
{
return *(this->functor_);
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::schedule(HANDLER handler,
const void *act,
uint32_t delay,
uint32_t interval)
{
BASE_GUARD_RETURN(LOCK, cf_mon, mutex_, 0);
BaseTimerNode_T<HANDLER>* timer_obj = node_pool_.pop_obj();
if(timer_obj != NULL)
{
uint32_t timer_id = get_free_node();
CBaseTimeValue cur_timer = CBaseTimeValue::get_time_value();
uint64_t distance = delay; //ֱԵǰʱΪ꣬һɨ20MS
if(cur_timer > start_time_)
distance = (cur_timer.msec() - start_time_.msec() + delay);// SELECT_DELAY;
distance = distance % (UNINT32_MAX);
timer_obj->set(handler, act, (uint32_t)(core_max(distance, 1)), interval, timer_id);
heap_[timer_id] = timer_obj;
used_num_ ++;
insert_node(timer_obj);
upcall_functor().registration(timer_obj->get_handler(), timer_id);
return timer_id;
}
return 0;
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::cancel_timer(uint32_t timer_id, const void **act)
{
BASE_GUARD(LOCK, cf_mon, mutex_);
if(timer_id < heap_size_ && heap_[timer_id] != NULL)
{
BaseTimerNode_T<HANDLER>* timer_obj = heap_[timer_id];
delete_node(timer_obj);
heap_[timer_id] = NULL;
if(used_num_ > 0)
used_num_ --;
freeTimers_.push_back(timer_id);
*act = timer_obj->get_act();
upcall_functor().cancel_timer(timer_obj->get_handler(), timer_id);
node_pool_.push_obj(timer_obj);
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::reset_timer(uint32_t timer_id, uint32_t delay, uint32_t interval /* = 0 */)
{
BASE_GUARD_RETURN(LOCK, cf_mon, mutex_, 0);
if(timer_id < heap_size_ && heap_[timer_id] != NULL)
{
BaseTimerNode_T<HANDLER>* timer_obj = heap_[timer_id];
delete_node(timer_obj);
timer_obj->set_internal(interval);
CBaseTimeValue cur_timer = CBaseTimeValue::get_time_value();
uint64_t distance = delay; // SELECT_DELAY; //ֱԵǰʱΪ꣬һɨ20MS
if(cur_timer > start_time_)
distance = (cur_timer.msec() - start_time_.msec() + delay); // SELECT_DELAY;
distance = distance % (UNINT32_MAX);
timer_obj->set_time_stamp(core_max(distance, 1));
insert_node(timer_obj);
return timer_id;
}
else
{
return 0;
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::expire()
{
BASE_GUARD_RETURN(LOCK, cf_mon, mutex_, 0);
uint32_t ret = SELECT_DELAY; //Ĭ20MS
CBaseTimeValue cur_timer = CBaseTimeValue::get_time_value();
if(cur_timer > prev_time_)
{
uint32_t scale = static_cast<uint32_t>((cur_timer.msec() - prev_time_.msec()));// SELECT_DELAY);
if(scale > 0)
{
ret = revolver(scale);
prev_time_ = cur_timer;
}
}
return ret;
}
template<class HANDLER, class FUNCTOR, class LOCK>
uint32_t CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::revolver(uint32_t scale)
{
//std::cout << "pos, first = " << rings_[0].get_pos() << ", second = " << rings_[1].get_pos()
// << ", third = " << rings_[2].get_pos() << ", fourth = " << rings_[3].get_pos() <<std::endl;
uint32_t ret = SELECT_DELAY;
uint8_t index = 0;
uint32_t rewind_scale = scale;
while(rewind_scale > 0)
{
index = 0;
if(rings_[index].cycle(rewind_scale, this)) //ɨһ
{
index ++;
uint32_t sc = 1;
while(rings_[index].cycle(sc, this))//ɨһ̶ֻ֣ǰƽ1
{
sc = 1;
index ++;
if(index >= RINGS_SIZE)
{
start_time_ = CBaseTimeValue::get_time_value();
break;
}
}
}
}
return ret;
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::ring_event(uint8_t ring_id, uint32_t timer_id)
{
if(heap_[timer_id] == NULL)
return;
BaseTimerNode_T<HANDLER>* timer_obj = heap_[timer_id];
if(ring_id == 0)
{
//ʱ֪ͨ
BaseTimerDispathInfo_T<HANDLER> info;
if(timer_obj != NULL)
{
timer_obj->get_dispatch_info(info);
this->dispatch_info(info, timer_id);
node_pool_.push_obj(timer_obj);
}
heap_[timer_id] = NULL;
if(used_num_ > 0)
used_num_ --;
freeTimers_.push_back(timer_id);
}
else if(ring_id < RINGS_SIZE)
{
//ƶRINGλã磬ڶӵijԪжʱӳ䵽һϽ·ֲ
insert_node(timer_obj);
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::insert_node(BaseTimerNode_T<HANDLER>* node)
{
uint32_t timer_id = node->get_timer_id();
uint8_t poss[RINGS_SIZE] = {0};
node->get_revolver_pos(poss[RINGS_SIZE - 1], poss[RINGS_SIZE - 2], poss[RINGS_SIZE - 3], poss[RINGS_SIZE - 4]);
//cout << "timer id = "<< timer_id << ", first = " << (uint16_t)poss[RINGS_SIZE - 4] << ",second = " << (uint16_t)poss[RINGS_SIZE - 3]
//<< ",third = " << (uint16_t)poss[RINGS_SIZE - 2] <<", fouth = " << (uint16_t)poss[RINGS_SIZE - 1] <<endl;
uint8_t index = RINGS_SIZE - 1;
while(!rings_[index].add_element(poss[index], timer_id))
{
if(index == 0)
break ;
index --;
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::delete_node(BaseTimerNode_T<HANDLER>* node)
{
uint32_t timer_id = node->get_timer_id();
uint8_t poss[RINGS_SIZE] = {0};
node->get_revolver_pos(poss[RINGS_SIZE - 1], poss[RINGS_SIZE - 2], poss[RINGS_SIZE - 3], poss[RINGS_SIZE - 4]);
for(uint8_t index = 0; index < RINGS_SIZE; index ++) //ÿϽɾ
{
rings_[index].delete_element(poss[index], timer_id);
}
}
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::dispatch_info(BaseTimerDispathInfo_T<HANDLER>& info, uint32_t timer_id)
{
upcall_functor().timer_out(info.handler_, info.act_, info.recurring_, timer_id);
}
#if _DEBUG
template<class HANDLER, class FUNCTOR, class LOCK>
void CTimerQueue_T<HANDLER, FUNCTOR, LOCK>::set_ring_id()
{
rings_[1].set_pos(255);
rings_[2].set_pos(0);
rings_[3].set_pos(0);
}
#endif
BASE_NAMESPACE_END_DECL
/////////////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>/**
* \file
* \brief PendSV_Handler() for ARMv6-M and ARMv7-M
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/internal/scheduler/getScheduler.hpp"
#include "distortos/internal/scheduler/Scheduler.hpp"
#include "distortos/chip/CMSIS-proxy.h"
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
#include "distortos/FATAL_ERROR.h"
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
namespace distortos
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
/**
* \brief Wrapper for check of stack pointer range
*
* If the check fails, FATAL_ERROR() is called.
*
* \param [in] stackPointer is the current thread's stack pointer value, including the frame which will be stacked
*/
void checkStackPointerWrapper(void* const stackPointer)
{
if (internal::getScheduler().getCurrentThreadControlBlock().getStack().checkStackPointer(stackPointer) == false)
FATAL_ERROR("Stack overflow detected!");
}
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
/**
* \brief Wrapper for void* distortos::internal::getScheduler().switchContext(void*)
*
* \param [in] stackPointer is the current value of current thread's stack pointer
*
* \return new thread's stack pointer
*/
void* schedulerSwitchContextWrapper(void* const stackPointer)
{
return internal::getScheduler().switchContext(stackPointer);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief PendSV_Handler() for ARMv6-M and ARMv7-M
*
* Performs the context switch.
*/
extern "C" __attribute__ ((naked)) void PendSV_Handler()
{
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
constexpr auto basepriValue = CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI << (8 - __NVIC_PRIO_BITS);
static_assert(basepriValue > 0 && basepriValue <= UINT8_MAX,
"Invalid CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI value!");
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
asm volatile
(
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
" mov r0, %[basepriValue] \n"
" msr basepri, r0 \n" // enable interrupt masking
#else // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" cpsid i \n" // disable interrupts
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" \n"
#ifdef __ARM_ARCH_6M__
" mrs r0, psp \n"
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
" push {r0, lr} \n"
" sub r0, r0, #0x20 \n"
" ldr r1, =%[checkStackPointerWrapper] \n"
" blx r1 \n"
" pop {r0, r1} \n"
" mov lr, r1 \n"
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
" sub r0, #0x10 \n"
" stmia r0!, {r4-r7} \n" // save lower half of current thread's context
" mov r4, r8 \n"
" mov r5, r9 \n"
" mov r6, r10 \n"
" mov r7, r11 \n"
" sub r0, #0x20 \n"
" stmia r0!, {r4-r7} \n" // save upper half of current thread's context
" sub r0, #0x10 \n"
" mov r4, lr \n"
" \n"
" ldr r1, =%[schedulerSwitchContext] \n"
" blx r1 \n" // switch context
" \n"
" mov lr, r4 \n"
" ldmia r0!, {r4-r7} \n" // load upper half of new thread's context
" mov r8, r4 \n"
" mov r9, r5 \n"
" mov r10, r6 \n"
" mov r11, r7 \n"
" ldmia r0!, {r4-r7} \n" // load lower half of new thread's context
" msr psp, r0 \n"
#else // !def __ARM_ARCH_6M__
" mrs r0, psp \n"
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
" push {r0, lr} \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" subeq r0, r0, #0x40 \n" // account for size of "floating-pont" context
" sub r0, r0, #0x28 \n"
#else // __FPU_PRESENT != 1 || __FPU_USED != 1
" sub r0, r0, #0x20 \n"
#endif // __FPU_PRESENT != 1 || __FPU_USED != 1
" bl %[checkStackPointerWrapper] \n" // switch context
" pop {r0, lr} \n"
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" vstmdbeq r0!, {s16-s31} \n" // save "floating-point" context of current thread
// save "regular" context of current thread (r12 is saved just to keep double-word alignment)
" stmdb r0!, {r4-r12, lr} \n"
#else // __FPU_PRESENT != 1 || __FPU_USED != 1
" stmdb r0!, {r4-r11} \n" // save context of current thread
" mov r4, lr \n"
#endif // __FPU_PRESENT != 1 || __FPU_USED != 1
" \n"
" bl %[schedulerSwitchContext] \n" // switch context
" \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" ldmia r0!, {r4-r12, lr} \n" // load "regular" context of new thread
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" vldmiaeq r0!, {s16-s31} \n" // load "floating-point" context of new thread
#else // __FPU_PRESENT != 1 || __FPU_USED != 1
" mov lr, r4 \n"
" ldmia r0!, {r4-r11} \n" // load context of new thread
#endif // __FPU_PRESENT != 1 || __FPU_USED != 1
" msr psp, r0 \n"
#endif // !def __ARM_ARCH_6M__
" \n"
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
" mov r0, #0 \n"
" msr basepri, r0 \n" // disable interrupt masking
#else // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" cpsie i \n" // enable interrupts
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" \n"
" bx lr \n" // return to new thread
::
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
[basepriValue] "i" (basepriValue),
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
[checkStackPointerWrapper] "i" (checkStackPointerWrapper),
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
[schedulerSwitchContext] "i" (schedulerSwitchContextWrapper)
);
__builtin_unreachable();
}
} // namespace distortos
<commit_msg>Remove wrong comment from PendSV_Handler() for ARMv6-M & ARMv7-M<commit_after>/**
* \file
* \brief PendSV_Handler() for ARMv6-M and ARMv7-M
*
* \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "distortos/internal/scheduler/getScheduler.hpp"
#include "distortos/internal/scheduler/Scheduler.hpp"
#include "distortos/chip/CMSIS-proxy.h"
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
#include "distortos/FATAL_ERROR.h"
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
namespace distortos
{
namespace
{
/*---------------------------------------------------------------------------------------------------------------------+
| local functions
+---------------------------------------------------------------------------------------------------------------------*/
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
/**
* \brief Wrapper for check of stack pointer range
*
* If the check fails, FATAL_ERROR() is called.
*
* \param [in] stackPointer is the current thread's stack pointer value, including the frame which will be stacked
*/
void checkStackPointerWrapper(void* const stackPointer)
{
if (internal::getScheduler().getCurrentThreadControlBlock().getStack().checkStackPointer(stackPointer) == false)
FATAL_ERROR("Stack overflow detected!");
}
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
/**
* \brief Wrapper for void* distortos::internal::getScheduler().switchContext(void*)
*
* \param [in] stackPointer is the current value of current thread's stack pointer
*
* \return new thread's stack pointer
*/
void* schedulerSwitchContextWrapper(void* const stackPointer)
{
return internal::getScheduler().switchContext(stackPointer);
}
} // namespace
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
/**
* \brief PendSV_Handler() for ARMv6-M and ARMv7-M
*
* Performs the context switch.
*/
extern "C" __attribute__ ((naked)) void PendSV_Handler()
{
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
constexpr auto basepriValue = CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI << (8 - __NVIC_PRIO_BITS);
static_assert(basepriValue > 0 && basepriValue <= UINT8_MAX,
"Invalid CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI value!");
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
asm volatile
(
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
" mov r0, %[basepriValue] \n"
" msr basepri, r0 \n" // enable interrupt masking
#else // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" cpsid i \n" // disable interrupts
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" \n"
#ifdef __ARM_ARCH_6M__
" mrs r0, psp \n"
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
" push {r0, lr} \n"
" sub r0, r0, #0x20 \n"
" ldr r1, =%[checkStackPointerWrapper] \n"
" blx r1 \n"
" pop {r0, r1} \n"
" mov lr, r1 \n"
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
" sub r0, #0x10 \n"
" stmia r0!, {r4-r7} \n" // save lower half of current thread's context
" mov r4, r8 \n"
" mov r5, r9 \n"
" mov r6, r10 \n"
" mov r7, r11 \n"
" sub r0, #0x20 \n"
" stmia r0!, {r4-r7} \n" // save upper half of current thread's context
" sub r0, #0x10 \n"
" mov r4, lr \n"
" \n"
" ldr r1, =%[schedulerSwitchContext] \n"
" blx r1 \n" // switch context
" \n"
" mov lr, r4 \n"
" ldmia r0!, {r4-r7} \n" // load upper half of new thread's context
" mov r8, r4 \n"
" mov r9, r5 \n"
" mov r10, r6 \n"
" mov r11, r7 \n"
" ldmia r0!, {r4-r7} \n" // load lower half of new thread's context
" msr psp, r0 \n"
#else // !def __ARM_ARCH_6M__
" mrs r0, psp \n"
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
" push {r0, lr} \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" subeq r0, r0, #0x40 \n" // account for size of "floating-pont" context
" sub r0, r0, #0x28 \n"
#else // __FPU_PRESENT != 1 || __FPU_USED != 1
" sub r0, r0, #0x20 \n"
#endif // __FPU_PRESENT != 1 || __FPU_USED != 1
" bl %[checkStackPointerWrapper] \n"
" pop {r0, lr} \n"
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" vstmdbeq r0!, {s16-s31} \n" // save "floating-point" context of current thread
// save "regular" context of current thread (r12 is saved just to keep double-word alignment)
" stmdb r0!, {r4-r12, lr} \n"
#else // __FPU_PRESENT != 1 || __FPU_USED != 1
" stmdb r0!, {r4-r11} \n" // save context of current thread
" mov r4, lr \n"
#endif // __FPU_PRESENT != 1 || __FPU_USED != 1
" \n"
" bl %[schedulerSwitchContext] \n" // switch context
" \n"
#if __FPU_PRESENT == 1 && __FPU_USED == 1
" ldmia r0!, {r4-r12, lr} \n" // load "regular" context of new thread
" tst lr, #(1 << 4) \n" // was floating-point used by the thread?
" it eq \n"
" vldmiaeq r0!, {s16-s31} \n" // load "floating-point" context of new thread
#else // __FPU_PRESENT != 1 || __FPU_USED != 1
" mov lr, r4 \n"
" ldmia r0!, {r4-r11} \n" // load context of new thread
#endif // __FPU_PRESENT != 1 || __FPU_USED != 1
" msr psp, r0 \n"
#endif // !def __ARM_ARCH_6M__
" \n"
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
" mov r0, #0 \n"
" msr basepri, r0 \n" // disable interrupt masking
#else // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" cpsie i \n" // enable interrupts
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI == 0
" \n"
" bx lr \n" // return to new thread
::
#if CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
[basepriValue] "i" (basepriValue),
#endif // CONFIG_ARCHITECTURE_ARMV7_M_KERNEL_BASEPRI != 0
#ifdef CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
[checkStackPointerWrapper] "i" (checkStackPointerWrapper),
#endif // def CONFIG_CHECK_STACK_POINTER_RANGE_ENABLE
[schedulerSwitchContext] "i" (schedulerSwitchContextWrapper)
);
__builtin_unreachable();
}
} // namespace distortos
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbSarRadiometricCalibrationToImageFilter.h"
namespace otb
{
namespace Wrapper
{
class SarRadiometricCalibration : public Application
{
public:
/** Standard class typedefs. */
typedef SarRadiometricCalibration Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(SarRadiometricCalibration, otb::Application);
typedef otb::SarRadiometricCalibrationToImageFilter<ComplexFloatImageType,
FloatImageType> CalibrationFilterType;
private:
void DoInit()
{
SetName("SarRadiometricCalibration");
SetDescription("Perform radiometric calibration of SAR images. Since OTB 5.2, following product types are supported. TerraSARX, Sentinel1 L1, Radarsat2.\n The application allow s one to read complex and non-complex(intensity) band images.");
// Documentation
SetDocName("SAR Radiometric calibration");
SetDocLongDescription("This application performs radiometric calibration of SAR images. Since OTB 5.2, following product types are supported. TerraSARX, Sentinel1 L1, Radarsat2.\n The application allows one to read images with complex and non-complex pixel types(intensity band). For non-complex type, the application reads it as std::complex() with imaginary part set to zero. ");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Calibration);
AddDocTag(Tags::SAR);
AddParameter(ParameterType_ComplexInputImage, "in", "Input Image");
SetParameterDescription("in", "Input complex image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output calibrated image. This image contains the backscatter (sigmaNought) of the input image.");
AddRAMParameter();
AddParameter(ParameterType_Empty, "noise", "Disable Noise");
SetParameterDescription("noise", "Flag to disable noise. For 5.2.0 release, the noise values are only read by TerraSARX product.");
MandatoryOff("noise");
AddParameter(ParameterType_Choice, "lut", "Lookup table sigma /gamma/ beta/ DN.");
SetParameterDescription("lut", "Lookup table values are not available with all SAR products. The products that provide lookup table with metadata are: Sentinel1, Radarsat2.");
AddChoice("lut.sigma", "Use sigma nought lookup");
SetParameterDescription("lut.sigma","Use Sigma nought lookup value from product metadata");
AddChoice("lut.gamma", "Use gamma nought lookup");
SetParameterDescription("lut.gamma","Use Gamma nought lookup value from product metadata");
AddChoice("lut.beta", "Use beta nought lookup");
SetParameterDescription("lut.beta","Use Beta nought lookup value from product metadata");
AddChoice("lut.dn", "Use DN value lookup");
SetParameterDescription("lut.dn","Use DN value lookup value from product metadata");
SetDefaultParameterInt("lut", 0);
// Doc example parameter settings
SetDocExampleParameterValue("in", "RSAT_imagery_HH.tif");
SetDocExampleParameterValue("out", "SarRadiometricCalibration.tif" );
}
void DoUpdateParameters()
{
}
void DoExecute()
{
// Get the input complex image
ComplexFloatImageType* floatComplexImage = GetParameterComplexFloatImage("in");
// Set the filer input
m_CalibrationFilter = CalibrationFilterType::New();
m_CalibrationFilter->SetInput(floatComplexImage);
if (IsParameterEnabled("noise"))
{
m_CalibrationFilter->SetEnableNoise(false);
}
short lut = 0;
lut = GetParameterInt("lut");
m_CalibrationFilter->SetLookupSelected(lut);
// Set the output image
SetParameterOutputImage("out", m_CalibrationFilter->GetOutput());
}
CalibrationFilterType::Pointer m_CalibrationFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::SarRadiometricCalibration)
<commit_msg>DOC: small edits in SAR calibration app description<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbSarRadiometricCalibrationToImageFilter.h"
namespace otb
{
namespace Wrapper
{
class SarRadiometricCalibration : public Application
{
public:
/** Standard class typedefs. */
typedef SarRadiometricCalibration Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(SarRadiometricCalibration, otb::Application);
typedef otb::SarRadiometricCalibrationToImageFilter<ComplexFloatImageType,
FloatImageType> CalibrationFilterType;
private:
void DoInit()
{
SetName("SarRadiometricCalibration");
SetDescription("Perform radiometric calibration of SAR images. Following sensors are supported: TerraSAR-X, Sentinel1 and Radarsat-2.Both Single Look Complex(SLC) and detected products are supported as input.\n");
// Documentation
SetDocName("SAR Radiometric calibration");
SetDocLongDescription("The objective of SAR calibration is to provide imagery in which the pixel values can be directly related to the radar backscatter of the scene. This application allows to compute Sigma Naught (Radiometric Calibration) for TerraSAR-X, Sentinel1 L1 and Radarsat-2 sensors. Metadata are automatically retrieved from image products.The application supports complex and non-complex images (SLC or detected products).\n");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Calibration);
AddDocTag(Tags::SAR);
AddParameter(ParameterType_ComplexInputImage, "in", "Input Image");
SetParameterDescription("in", "Input complex image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output calibrated image. This image contains the backscatter (sigmaNought) of the input image.");
AddRAMParameter();
AddParameter(ParameterType_Empty, "noise", "Disable Noise");
SetParameterDescription("noise", "Flag to disable noise. For 5.2.0 release, the noise values are only read by TerraSARX product.");
MandatoryOff("noise");
AddParameter(ParameterType_Choice, "lut", "Lookup table sigma /gamma/ beta/ DN.");
SetParameterDescription("lut", "Lookup table values are not available with all SAR products. Products that provide lookup table with metadata are: Sentinel1, Radarsat2.");
AddChoice("lut.sigma", "Use sigma nought lookup");
SetParameterDescription("lut.sigma","Use Sigma nought lookup value from product metadata");
AddChoice("lut.gamma", "Use gamma nought lookup");
SetParameterDescription("lut.gamma","Use Gamma nought lookup value from product metadata");
AddChoice("lut.beta", "Use beta nought lookup");
SetParameterDescription("lut.beta","Use Beta nought lookup value from product metadata");
AddChoice("lut.dn", "Use DN value lookup");
SetParameterDescription("lut.dn","Use DN value lookup value from product metadata");
SetDefaultParameterInt("lut", 0);
// Doc example parameter settings
SetDocExampleParameterValue("in", "RSAT_imagery_HH.tif");
SetDocExampleParameterValue("out", "SarRadiometricCalibration.tif" );
}
void DoUpdateParameters()
{
}
void DoExecute()
{
// Get the input complex image
ComplexFloatImageType* floatComplexImage = GetParameterComplexFloatImage("in");
// Set the filer input
m_CalibrationFilter = CalibrationFilterType::New();
m_CalibrationFilter->SetInput(floatComplexImage);
if (IsParameterEnabled("noise"))
{
m_CalibrationFilter->SetEnableNoise(false);
}
short lut = 0;
lut = GetParameterInt("lut");
m_CalibrationFilter->SetLookupSelected(lut);
// Set the output image
SetParameterOutputImage("out", m_CalibrationFilter->GetOutput());
}
CalibrationFilterType::Pointer m_CalibrationFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::SarRadiometricCalibration)
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/gtk/tab_contents/chrome_web_contents_view_delegate_gtk.h"
#include <map>
#include "base/lazy_instance.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/tab_contents/web_drag_bookmark_handler_gtk.h"
#include "chrome/browser/ui/gtk/constrained_window_gtk.h"
#include "chrome/browser/ui/gtk/tab_contents/render_view_context_menu_gtk.h"
#include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/base/gtk/focus_store_gtk.h"
#include "ui/base/gtk/gtk_floating_container.h"
namespace {
const char kViewDelegateUserDataKey[] = "ChromeWebContentsViewDelegateGtk";
class ViewDelegateUserData : public base::SupportsUserData::Data {
public:
explicit ViewDelegateUserData(ChromeWebContentsViewDelegateGtk* view_delegate)
: view_delegate_(view_delegate) {}
virtual ~ViewDelegateUserData() {}
ChromeWebContentsViewDelegateGtk* view_delegate() { return view_delegate_; }
private:
ChromeWebContentsViewDelegateGtk* view_delegate_; // unowned
};
} // namespace
ChromeWebContentsViewDelegateGtk* ChromeWebContentsViewDelegateGtk::GetFor(
content::WebContents* web_contents) {
ViewDelegateUserData* user_data = static_cast<ViewDelegateUserData*>(
web_contents->GetUserData(&kViewDelegateUserDataKey));
return user_data ? user_data->view_delegate() : NULL;
}
ChromeWebContentsViewDelegateGtk::ChromeWebContentsViewDelegateGtk(
content::WebContents* web_contents)
: floating_(gtk_floating_container_new()),
constrained_window_(NULL),
web_contents_(web_contents),
expanded_container_(NULL),
focus_store_(NULL) {
gtk_widget_set_name(floating_.get(), "chrome-tab-contents-view");
g_signal_connect(floating_.get(), "set-floating-position",
G_CALLBACK(OnSetFloatingPositionThunk), this);
// Stash this in the WebContents.
web_contents->SetUserData(&kViewDelegateUserDataKey,
new ViewDelegateUserData(this));
}
ChromeWebContentsViewDelegateGtk::~ChromeWebContentsViewDelegateGtk() {
floating_.Destroy();
}
void ChromeWebContentsViewDelegateGtk::AttachConstrainedWindow(
ConstrainedWindowGtk* constrained_window) {
DCHECK(constrained_window_ == NULL);
constrained_window_ = constrained_window;
gtk_floating_container_add_floating(GTK_FLOATING_CONTAINER(floating_.get()),
constrained_window->widget());
}
void ChromeWebContentsViewDelegateGtk::RemoveConstrainedWindow(
ConstrainedWindowGtk* constrained_window) {
DCHECK(constrained_window == constrained_window_);
constrained_window_ = NULL;
gtk_container_remove(GTK_CONTAINER(floating_.get()),
constrained_window->widget());
}
void ChromeWebContentsViewDelegateGtk::Initialize(
GtkWidget* expanded_container, ui::FocusStoreGtk* focus_store) {
expanded_container_ = expanded_container;
focus_store_ = focus_store;
// We install a chrome specific handler to intercept bookmark drags for the
// bookmark manager/extension API.
bookmark_handler_gtk_.reset(new WebDragBookmarkHandlerGtk);
gtk_container_add(GTK_CONTAINER(floating_.get()), expanded_container);
gtk_widget_show(floating_.get());
}
gfx::NativeView ChromeWebContentsViewDelegateGtk::GetNativeView() const {
return floating_.get();
}
void ChromeWebContentsViewDelegateGtk::Focus() {
if (!constrained_window_) {
GtkWidget* widget = web_contents_->GetView()->GetContentNativeView();
if (widget)
gtk_widget_grab_focus(widget);
}
}
gboolean ChromeWebContentsViewDelegateGtk::OnNativeViewFocusEvent(
GtkWidget* widget,
GtkDirectionType type,
gboolean* return_value) {
// If we are showing a constrained window, don't allow the native view to take
// focus.
if (constrained_window_) {
// If we return false, it will revert to the default handler, which will
// take focus. We don't want that. But if we return true, the event will
// stop being propagated, leaving focus wherever it is currently. That is
// also bad. So we return false to let the default handler run, but take
// focus first so as to trick it into thinking the view was already focused
// and allowing the event to propagate.
gtk_widget_grab_focus(widget);
*return_value = FALSE;
return TRUE;
}
// Let the default WebContentsViewGtk::OnFocus() behaviour run.
return FALSE;
}
void ChromeWebContentsViewDelegateGtk::ShowContextMenu(
const content::ContextMenuParams& params,
content::ContextMenuSourceType type) {
// Find out the RenderWidgetHostView that corresponds to the render widget on
// which this context menu is showed, so that we can retrieve the last mouse
// down event on the render widget and use it as the timestamp of the
// activation event to show the context menu.
content::RenderWidgetHostView* view = NULL;
if (params.custom_context.render_widget_id !=
content::CustomContextMenuContext::kCurrentRenderWidget) {
content::RenderWidgetHost* host =
web_contents_->GetRenderProcessHost()->GetRenderWidgetHostByID(
params.custom_context.render_widget_id);
if (!host) {
NOTREACHED();
return;
}
view = host->GetView();
} else {
view = web_contents_->GetRenderWidgetHostView();
}
context_menu_.reset(
new RenderViewContextMenuGtk(web_contents_, params, view));
context_menu_->Init();
gfx::Rect bounds;
web_contents_->GetView()->GetContainerBounds(&bounds);
gfx::Point point = bounds.origin();
point.Offset(params.x, params.y);
context_menu_->Popup(point);
}
content::WebDragDestDelegate*
ChromeWebContentsViewDelegateGtk::GetDragDestDelegate() {
return bookmark_handler_gtk_.get();
}
void ChromeWebContentsViewDelegateGtk::OnSetFloatingPosition(
GtkWidget* floating_container, GtkAllocation* allocation) {
if (!constrained_window_)
return;
// Place each WebContentsModalDialog in the center of the view.
GtkWidget* widget = constrained_window_->widget();
DCHECK(gtk_widget_get_parent(widget) == floating_.get());
GtkRequisition requisition;
gtk_widget_size_request(widget, &requisition);
GValue value = { 0, };
g_value_init(&value, G_TYPE_INT);
int child_x = std::max((allocation->width - requisition.width) / 2, 0);
g_value_set_int(&value, child_x);
gtk_container_child_set_property(GTK_CONTAINER(floating_container),
widget, "x", &value);
int child_y = std::max((allocation->height - requisition.height) / 2, 0);
g_value_set_int(&value, child_y);
gtk_container_child_set_property(GTK_CONTAINER(floating_container),
widget, "y", &value);
g_value_unset(&value);
}
namespace chrome {
content::WebContentsViewDelegate* CreateWebContentsViewDelegate(
content::WebContents* web_contents) {
return new ChromeWebContentsViewDelegateGtk(web_contents);
}
} // namespace chrome
<commit_msg>Don't show empty popup menus on Gtk.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/gtk/tab_contents/chrome_web_contents_view_delegate_gtk.h"
#include <map>
#include "base/lazy_instance.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/tab_contents/web_drag_bookmark_handler_gtk.h"
#include "chrome/browser/ui/gtk/constrained_window_gtk.h"
#include "chrome/browser/ui/gtk/tab_contents/render_view_context_menu_gtk.h"
#include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/base/gtk/focus_store_gtk.h"
#include "ui/base/gtk/gtk_floating_container.h"
namespace {
const char kViewDelegateUserDataKey[] = "ChromeWebContentsViewDelegateGtk";
class ViewDelegateUserData : public base::SupportsUserData::Data {
public:
explicit ViewDelegateUserData(ChromeWebContentsViewDelegateGtk* view_delegate)
: view_delegate_(view_delegate) {}
virtual ~ViewDelegateUserData() {}
ChromeWebContentsViewDelegateGtk* view_delegate() { return view_delegate_; }
private:
ChromeWebContentsViewDelegateGtk* view_delegate_; // unowned
};
} // namespace
ChromeWebContentsViewDelegateGtk* ChromeWebContentsViewDelegateGtk::GetFor(
content::WebContents* web_contents) {
ViewDelegateUserData* user_data = static_cast<ViewDelegateUserData*>(
web_contents->GetUserData(&kViewDelegateUserDataKey));
return user_data ? user_data->view_delegate() : NULL;
}
ChromeWebContentsViewDelegateGtk::ChromeWebContentsViewDelegateGtk(
content::WebContents* web_contents)
: floating_(gtk_floating_container_new()),
constrained_window_(NULL),
web_contents_(web_contents),
expanded_container_(NULL),
focus_store_(NULL) {
gtk_widget_set_name(floating_.get(), "chrome-tab-contents-view");
g_signal_connect(floating_.get(), "set-floating-position",
G_CALLBACK(OnSetFloatingPositionThunk), this);
// Stash this in the WebContents.
web_contents->SetUserData(&kViewDelegateUserDataKey,
new ViewDelegateUserData(this));
}
ChromeWebContentsViewDelegateGtk::~ChromeWebContentsViewDelegateGtk() {
floating_.Destroy();
}
void ChromeWebContentsViewDelegateGtk::AttachConstrainedWindow(
ConstrainedWindowGtk* constrained_window) {
DCHECK(constrained_window_ == NULL);
constrained_window_ = constrained_window;
gtk_floating_container_add_floating(GTK_FLOATING_CONTAINER(floating_.get()),
constrained_window->widget());
}
void ChromeWebContentsViewDelegateGtk::RemoveConstrainedWindow(
ConstrainedWindowGtk* constrained_window) {
DCHECK(constrained_window == constrained_window_);
constrained_window_ = NULL;
gtk_container_remove(GTK_CONTAINER(floating_.get()),
constrained_window->widget());
}
void ChromeWebContentsViewDelegateGtk::Initialize(
GtkWidget* expanded_container, ui::FocusStoreGtk* focus_store) {
expanded_container_ = expanded_container;
focus_store_ = focus_store;
// We install a chrome specific handler to intercept bookmark drags for the
// bookmark manager/extension API.
bookmark_handler_gtk_.reset(new WebDragBookmarkHandlerGtk);
gtk_container_add(GTK_CONTAINER(floating_.get()), expanded_container);
gtk_widget_show(floating_.get());
}
gfx::NativeView ChromeWebContentsViewDelegateGtk::GetNativeView() const {
return floating_.get();
}
void ChromeWebContentsViewDelegateGtk::Focus() {
if (!constrained_window_) {
GtkWidget* widget = web_contents_->GetView()->GetContentNativeView();
if (widget)
gtk_widget_grab_focus(widget);
}
}
gboolean ChromeWebContentsViewDelegateGtk::OnNativeViewFocusEvent(
GtkWidget* widget,
GtkDirectionType type,
gboolean* return_value) {
// If we are showing a constrained window, don't allow the native view to take
// focus.
if (constrained_window_) {
// If we return false, it will revert to the default handler, which will
// take focus. We don't want that. But if we return true, the event will
// stop being propagated, leaving focus wherever it is currently. That is
// also bad. So we return false to let the default handler run, but take
// focus first so as to trick it into thinking the view was already focused
// and allowing the event to propagate.
gtk_widget_grab_focus(widget);
*return_value = FALSE;
return TRUE;
}
// Let the default WebContentsViewGtk::OnFocus() behaviour run.
return FALSE;
}
void ChromeWebContentsViewDelegateGtk::ShowContextMenu(
const content::ContextMenuParams& params,
content::ContextMenuSourceType type) {
// Find out the RenderWidgetHostView that corresponds to the render widget on
// which this context menu is showed, so that we can retrieve the last mouse
// down event on the render widget and use it as the timestamp of the
// activation event to show the context menu.
content::RenderWidgetHostView* view = NULL;
if (params.custom_context.render_widget_id !=
content::CustomContextMenuContext::kCurrentRenderWidget) {
content::RenderWidgetHost* host =
web_contents_->GetRenderProcessHost()->GetRenderWidgetHostByID(
params.custom_context.render_widget_id);
if (!host) {
NOTREACHED();
return;
}
view = host->GetView();
} else {
view = web_contents_->GetRenderWidgetHostView();
}
context_menu_.reset(
new RenderViewContextMenuGtk(web_contents_, params, view));
context_menu_->Init();
// Don't show empty menus.
if (context_menu_->menu_model().GetItemCount() == 0)
return;
gfx::Rect bounds;
web_contents_->GetView()->GetContainerBounds(&bounds);
gfx::Point point = bounds.origin();
point.Offset(params.x, params.y);
context_menu_->Popup(point);
}
content::WebDragDestDelegate*
ChromeWebContentsViewDelegateGtk::GetDragDestDelegate() {
return bookmark_handler_gtk_.get();
}
void ChromeWebContentsViewDelegateGtk::OnSetFloatingPosition(
GtkWidget* floating_container, GtkAllocation* allocation) {
if (!constrained_window_)
return;
// Place each WebContentsModalDialog in the center of the view.
GtkWidget* widget = constrained_window_->widget();
DCHECK(gtk_widget_get_parent(widget) == floating_.get());
GtkRequisition requisition;
gtk_widget_size_request(widget, &requisition);
GValue value = { 0, };
g_value_init(&value, G_TYPE_INT);
int child_x = std::max((allocation->width - requisition.width) / 2, 0);
g_value_set_int(&value, child_x);
gtk_container_child_set_property(GTK_CONTAINER(floating_container),
widget, "x", &value);
int child_y = std::max((allocation->height - requisition.height) / 2, 0);
g_value_set_int(&value, child_y);
gtk_container_child_set_property(GTK_CONTAINER(floating_container),
widget, "y", &value);
g_value_unset(&value);
}
namespace chrome {
content::WebContentsViewDelegate* CreateWebContentsViewDelegate(
content::WebContents* web_contents) {
return new ChromeWebContentsViewDelegateGtk(web_contents);
}
} // namespace chrome
<|endoftext|>
|
<commit_before>#include <cutehmi/dataacquisition/Schema.hpp>
#include <cutehmi/dataacquisition/Exception.hpp>
#include "../../../cutehmi.dirs.hpp"
#include <QFile>
#include <QSqlRecord>
namespace cutehmi {
namespace dataacquisition {
Schema::Schema(QObject * parent):
shareddatabase::DataObject(parent),
m(new Members)
{
}
QString Schema::name() const
{
return m->name;
}
void Schema::setName(const QString & name)
{
if (m->name != name) {
m->name = name;
emit nameChanged();
}
}
QString Schema::user() const
{
return m->user;
}
void Schema::setUser(const QString & user)
{
if (m->user != user) {
m->user = user;
emit userChanged();
}
}
void Schema::create()
{
worker([this](QSqlDatabase & db) {
bool warning = false;
bool error = false;
if (db.driverName() == "QPSQL") {
QSqlQuery query(db);
try {
CUTEHMI_DEBUG("Creating schema...");
QString queryString = readScript(POSTGRESQL_SCRIPTS_SUBDIR, "create.sql").arg(name());
CUTEHMI_DEBUG("SQL query:\n```\n" << queryString + "\n```");
if (!query.exec(queryString))
error = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
error = true;
}
if (!user().isEmpty()) {
CUTEHMI_DEBUG("Setting schema owner...");
const char * alterSchemaQuery = R"SQL(
ALTER SCHEMA %1 OWNER TO %2;
)SQL";
if (!query.exec(QString(alterSchemaQuery).arg(name(), user())))
warning = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
}
} else if (db.driverName() == "QSQLITE") {
QSqlQuery query(db);
try {
CUTEHMI_DEBUG("Creating schema...");
QString queryString = readScript(SQLITE_SCRIPTS_SUBDIR, "create.sql").arg(name());
QStringList queryList = queryString.split(';');
queryList.removeLast(); // Remove empty query.
for (auto queryIt = queryList.begin(); queryIt != queryList.end(); ++queryIt) {
CUTEHMI_DEBUG("SQL query:\n```\n" << *queryIt + "\n```");
if (!query.exec(*queryIt))
error = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
}
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
error = true;
}
} else {
emit errored(CUTEHMI_ERROR(tr("Driver '%1' is not supported.").arg(db.driverName())));
error = true;
}
if (error)
Notification::Critical(tr("Failed to create '%1' schema.").arg(name()));
else if (warning)
Notification::Warning(tr("Created '%1' schema although the operation wasn't clean.").arg(name()));
else
Notification::Info(tr("Successfully created '%1' schema.").arg(name()));
if (error)
emit created(false);
else
emit created(true);
})->work();
}
void Schema::drop()
{
worker([this](QSqlDatabase & db) {
bool warning = false;
bool error = false;
if (db.driverName() == "QPSQL") {
QSqlQuery query(db);
try {
CUTEHMI_DEBUG("Dropping schema...");
QString queryString = readScript(POSTGRESQL_SCRIPTS_SUBDIR, "drop.sql").arg(name());
CUTEHMI_DEBUG("SQL query:\n```\n" << queryString + "\n```");
if (!query.exec(queryString))
error = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
error = true;
}
} else if (db.driverName() == "QSQLITE") {
QSqlQuery query(db);
try {
CUTEHMI_DEBUG("Dropping schema...");
QString queryString = readScript(SQLITE_SCRIPTS_SUBDIR, "drop.sql").arg(name());
QStringList queryList = queryString.split(';');
queryList.removeLast(); // Remove empty query.
for (auto queryIt = queryList.begin(); queryIt != queryList.end(); ++queryIt) {
CUTEHMI_DEBUG("SQL query:\n```\n" << *queryIt + "\n```");
if (!query.exec(*queryIt))
warning = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
}
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
error = true;
}
} else {
emit errored(CUTEHMI_ERROR(tr("Driver '%1' is not supported.").arg(db.driverName())));
error = true;
}
if (error)
Notification::Critical(tr("Failed to drop '%1' schema.").arg(name()));
else if (warning)
Notification::Warning(tr("Dropped '%1' schema although the operation wasn't clean.").arg(name()));
else
Notification::Info(tr("Dropped '%1' schema.").arg(name()));
if (error)
emit dropped(false);
else
emit dropped(true);
})->work();
}
void Schema::validate()
{
worker([this](QSqlDatabase & db) {
if (db.driverName() == "QPSQL") {
QSqlQuery query(db);
bool result = true;
result &= validatePostgresTable("tag", query);
result &= validatePostgresTable("history_int", query);
result &= validatePostgresTable("history_bool", query);
result &= validatePostgresTable("history_real", query);
result &= validatePostgresTable("event_int", query);
result &= validatePostgresTable("event_bool", query);
result &= validatePostgresTable("event_real", query);
result &= validatePostgresTable("recency_int", query);
result &= validatePostgresTable("recency_bool", query);
result &= validatePostgresTable("recency_real", query);
emit validated(result);
} else if (db.driverName() == "QSQLITE") {
QSqlQuery query(db);
bool result = true;
result &= validateSqliteTable("tag", query);
result &= validateSqliteTable("history_int", query);
result &= validateSqliteTable("history_bool", query);
result &= validateSqliteTable("history_real", query);
result &= validateSqliteTable("event_int", query);
result &= validateSqliteTable("event_bool", query);
result &= validateSqliteTable("event_real", query);
result &= validateSqliteTable("recency_int", query);
result &= validateSqliteTable("recency_bool", query);
result &= validateSqliteTable("recency_real", query);
emit validated(result);
} else {
emit errored(CUTEHMI_ERROR(tr("Driver '%1' is not supported.").arg(db.driverName())));
emit validated(false);
}
})->work();
}
bool Schema::validatePostgresTable(const QString & tableName, QSqlQuery & query)
{
bool result = true;
CUTEHMI_DEBUG("Checking if '" << tableName << "' table exists...");
const char * tableExistsQuery = R"SQL(
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = '%1' AND table_name = '%2'
);
)SQL";
query.exec(QString(tableExistsQuery).arg(name(), tableName));
pushError(query.lastError(), query.lastQuery());
int existsIndex = query.record().indexOf("exists");
if (query.first())
if (!query.value(existsIndex).toBool()) {
emit errored(CUTEHMI_ERROR(QObject::tr("Table '%1' does not exist in schema '%2'.").arg(tableName, name())));
result = false;
}
query.finish();
return result;
}
bool Schema::validateSqliteTable(const QString & tableName, QSqlQuery & query)
{
bool result = true;
CUTEHMI_DEBUG("Checking if '" << tableName << "' table exists...");
const char * tableExistsQuery = R"SQL(
SELECT name FROM sqlite_master WHERE type='table' AND name='%1.%2';
)SQL";
query.exec(QString(tableExistsQuery).arg(name(), tableName));
pushError(query.lastError(), query.lastQuery());
if (!query.first()) {
emit errored(CUTEHMI_ERROR(QObject::tr("Table '%1' does not exist in schema '%2'.").arg(tableName, name())));
result = false;
}
query.finish();
return result;
}
QString Schema::readScript(const QString & dbms, const QString & scriptName) const
{
QFile file(QString(CUTEHMI_DIRS_TOOL_RELATIVE_PATH) + "/" + SQL_SCRIPTS_SUBDIR + "/" + dbms + "/" + scriptName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
throw Exception(QString("Could not open file '%1'").arg(file.fileName()));
return QTextStream(& file).readAll();
}
}
}
//(c)C: Copyright © 2020-2022, Michał Policht <michal@policht.pl>, Yuri Chornoivan <yurchor@ukr.net>. All rights reserved.
//(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI 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.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>.
//(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.
//(c)C: 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:
//(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//(c)C: 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.
<commit_msg>Add debug messages for validating schema<commit_after>#include <cutehmi/dataacquisition/Schema.hpp>
#include <cutehmi/dataacquisition/Exception.hpp>
#include "../../../cutehmi.dirs.hpp"
#include <QFile>
#include <QSqlRecord>
namespace cutehmi {
namespace dataacquisition {
Schema::Schema(QObject * parent):
shareddatabase::DataObject(parent),
m(new Members)
{
}
QString Schema::name() const
{
return m->name;
}
void Schema::setName(const QString & name)
{
if (m->name != name) {
m->name = name;
emit nameChanged();
}
}
QString Schema::user() const
{
return m->user;
}
void Schema::setUser(const QString & user)
{
if (m->user != user) {
m->user = user;
emit userChanged();
}
}
void Schema::create()
{
worker([this](QSqlDatabase & db) {
bool warning = false;
bool error = false;
if (db.driverName() == "QPSQL") {
CUTEHMI_DEBUG("Creating schema...");
QSqlQuery query(db);
try {
QString queryString = readScript(POSTGRESQL_SCRIPTS_SUBDIR, "create.sql").arg(name());
CUTEHMI_DEBUG("SQL query:\n```\n" << queryString + "\n```");
if (!query.exec(queryString))
error = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
error = true;
}
if (!user().isEmpty()) {
CUTEHMI_DEBUG("Setting schema owner...");
const char * alterSchemaQuery = R"SQL(
ALTER SCHEMA %1 OWNER TO %2;
)SQL";
if (!query.exec(QString(alterSchemaQuery).arg(name(), user())))
warning = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
}
} else if (db.driverName() == "QSQLITE") {
CUTEHMI_DEBUG("Creating schema...");
QSqlQuery query(db);
try {
QString queryString = readScript(SQLITE_SCRIPTS_SUBDIR, "create.sql").arg(name());
QStringList queryList = queryString.split(';');
queryList.removeLast(); // Remove empty query.
for (auto queryIt = queryList.begin(); queryIt != queryList.end(); ++queryIt) {
CUTEHMI_DEBUG("SQL query:\n```\n" << *queryIt + "\n```");
if (!query.exec(*queryIt))
error = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
}
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
error = true;
}
} else {
emit errored(CUTEHMI_ERROR(tr("Driver '%1' is not supported.").arg(db.driverName())));
error = true;
}
if (error)
Notification::Critical(tr("Failed to create '%1' schema.").arg(name()));
else if (warning)
Notification::Warning(tr("Created '%1' schema although the operation wasn't clean.").arg(name()));
else
Notification::Info(tr("Successfully created '%1' schema.").arg(name()));
if (error)
emit created(false);
else
emit created(true);
})->work();
}
void Schema::drop()
{
worker([this](QSqlDatabase & db) {
bool warning = false;
bool error = false;
if (db.driverName() == "QPSQL") {
CUTEHMI_DEBUG("Dropping schema...");
QSqlQuery query(db);
try {
QString queryString = readScript(POSTGRESQL_SCRIPTS_SUBDIR, "drop.sql").arg(name());
CUTEHMI_DEBUG("SQL query:\n```\n" << queryString + "\n```");
if (!query.exec(queryString))
error = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
error = true;
}
} else if (db.driverName() == "QSQLITE") {
CUTEHMI_DEBUG("Dropping schema...");
QSqlQuery query(db);
try {
QString queryString = readScript(SQLITE_SCRIPTS_SUBDIR, "drop.sql").arg(name());
QStringList queryList = queryString.split(';');
queryList.removeLast(); // Remove empty query.
for (auto queryIt = queryList.begin(); queryIt != queryList.end(); ++queryIt) {
CUTEHMI_DEBUG("SQL query:\n```\n" << *queryIt + "\n```");
if (!query.exec(*queryIt))
warning = true;
pushError(query.lastError(), query.lastQuery());
query.finish();
}
} catch (const Exception & e) {
CUTEHMI_CRITICAL(e.what());
error = true;
}
} else {
emit errored(CUTEHMI_ERROR(tr("Driver '%1' is not supported.").arg(db.driverName())));
error = true;
}
if (error)
Notification::Critical(tr("Failed to drop '%1' schema.").arg(name()));
else if (warning)
Notification::Warning(tr("Dropped '%1' schema although the operation wasn't clean.").arg(name()));
else
Notification::Info(tr("Dropped '%1' schema.").arg(name()));
if (error)
emit dropped(false);
else
emit dropped(true);
})->work();
}
void Schema::validate()
{
worker([this](QSqlDatabase & db) {
if (db.driverName() == "QPSQL") {
CUTEHMI_DEBUG("Validating schema...");
QSqlQuery query(db);
bool result = true;
result &= validatePostgresTable("tag", query);
result &= validatePostgresTable("history_int", query);
result &= validatePostgresTable("history_bool", query);
result &= validatePostgresTable("history_real", query);
result &= validatePostgresTable("event_int", query);
result &= validatePostgresTable("event_bool", query);
result &= validatePostgresTable("event_real", query);
result &= validatePostgresTable("recency_int", query);
result &= validatePostgresTable("recency_bool", query);
result &= validatePostgresTable("recency_real", query);
emit validated(result);
} else if (db.driverName() == "QSQLITE") {
CUTEHMI_DEBUG("Validating schema...");
QSqlQuery query(db);
bool result = true;
result &= validateSqliteTable("tag", query);
result &= validateSqliteTable("history_int", query);
result &= validateSqliteTable("history_bool", query);
result &= validateSqliteTable("history_real", query);
result &= validateSqliteTable("event_int", query);
result &= validateSqliteTable("event_bool", query);
result &= validateSqliteTable("event_real", query);
result &= validateSqliteTable("recency_int", query);
result &= validateSqliteTable("recency_bool", query);
result &= validateSqliteTable("recency_real", query);
emit validated(result);
} else {
emit errored(CUTEHMI_ERROR(tr("Driver '%1' is not supported.").arg(db.driverName())));
emit validated(false);
}
})->work();
}
bool Schema::validatePostgresTable(const QString & tableName, QSqlQuery & query)
{
bool result = true;
CUTEHMI_DEBUG("Checking if '" << tableName << "' table exists...");
const char * tableExistsQuery = R"SQL(
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = '%1' AND table_name = '%2'
);
)SQL";
query.exec(QString(tableExistsQuery).arg(name(), tableName));
pushError(query.lastError(), query.lastQuery());
int existsIndex = query.record().indexOf("exists");
if (query.first())
if (!query.value(existsIndex).toBool()) {
emit errored(CUTEHMI_ERROR(QObject::tr("Table '%1' does not exist in schema '%2'.").arg(tableName, name())));
result = false;
}
query.finish();
return result;
}
bool Schema::validateSqliteTable(const QString & tableName, QSqlQuery & query)
{
bool result = true;
CUTEHMI_DEBUG("Checking if '" << tableName << "' table exists...");
const char * tableExistsQuery = R"SQL(
SELECT name FROM sqlite_master WHERE type='table' AND name='%1.%2';
)SQL";
query.exec(QString(tableExistsQuery).arg(name(), tableName));
pushError(query.lastError(), query.lastQuery());
if (!query.first()) {
emit errored(CUTEHMI_ERROR(QObject::tr("Table '%1' does not exist in schema '%2'.").arg(tableName, name())));
result = false;
}
query.finish();
return result;
}
QString Schema::readScript(const QString & dbms, const QString & scriptName) const
{
QFile file(QString(CUTEHMI_DIRS_TOOL_RELATIVE_PATH) + "/" + SQL_SCRIPTS_SUBDIR + "/" + dbms + "/" + scriptName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
throw Exception(QString("Could not open file '%1'").arg(file.fileName()));
return QTextStream(& file).readAll();
}
}
}
//(c)C: Copyright © 2020-2022, Michał Policht <michal@policht.pl>, Yuri Chornoivan <yurchor@ukr.net>. All rights reserved.
//(c)C: SPDX-License-Identifier: LGPL-3.0-or-later OR MIT
//(c)C: This file is a part of CuteHMI.
//(c)C: CuteHMI is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
//(c)C: CuteHMI 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.
//(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>.
//(c)C: Additionally, this file is licensed under terms of MIT license as expressed below.
//(c)C: 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:
//(c)C: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//(c)C: 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.
<|endoftext|>
|
<commit_before>/*****************************************************************************/
/**
* @file LabColor.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id$
*/
/*****************************************************************************/
#include "LabColor.h"
#include "XYZColor.h"
#include "MshColor.h"
namespace
{
//const kvs::Vec3 ReferenceWhite( 1.0, 1.0, 1.0 );
//const kvs::Vec3 ReferenceWhite( 0.964221, 1.0, 0.825211 ); // D50
const kvs::Vec3 ReferenceWhite( 0.95047, 1.0, 1.08883 ); // D65
kvs::Real32 f( const kvs::Real32 t )
{
if ( t > 0.008856 ) { return std::pow( t, 1.0 / 3.0 ); }
else { return 7.787037 * t + 16.0 / 116.0; }
}
kvs::Real32 finv( const kvs::Real32 t )
{
if ( t > 0.008856 ) { return std::pow( t, 3.0 ); }
else { return ( t - 16.0 / 116.0 ) / 7.787037; }
}
kvs::LabColor XYZ2Lab( const kvs::XYZColor& xyz )
{
const kvs::Real32 Xn = ReferenceWhite.x();
const kvs::Real32 Yn = ReferenceWhite.y();
const kvs::Real32 Zn = ReferenceWhite.z();
const kvs::Real32 X = xyz.x();
const kvs::Real32 Y = xyz.y();
const kvs::Real32 Z = xyz.z();
const kvs::Real32 l = 116.0 * ( f( Y / Yn ) - 16.0 / 116.0 );
const kvs::Real32 a = 500.0 * ( f( X / Xn ) - f( Y / Yn ) );
const kvs::Real32 b = 200.0 * ( f( Y / Yn ) - f( Z / Zn ) );
return kvs::LabColor( l, a, b );
}
kvs::XYZColor Lab2XYZ( const kvs::LabColor& lab )
{
const kvs::Real32 Xn = ReferenceWhite.x();
const kvs::Real32 Yn = ReferenceWhite.y();
const kvs::Real32 Zn = ReferenceWhite.z();
const kvs::Real32 l = lab.l();
const kvs::Real32 a = lab.a();
const kvs::Real32 b = lab.b();
const kvs::Real32 y = ( l + 16.0 ) / 116.0;
const kvs::Real32 x = a / 500.0 + y;
const kvs::Real32 z = y - b / 200.0;
const kvs::Real32 X = Xn * finv( x );
const kvs::Real32 Y = Yn * finv( y );
const kvs::Real32 Z = Zn * finv( z );
return kvs::XYZColor( X, Y, Z );
}
}
namespace kvs
{
LabColor::LabColor( kvs::Real32 l, kvs::Real32 a, kvs::Real32 b ):
m_l( l ),
m_a( a ),
m_b( b )
{
}
LabColor::LabColor( const kvs::Vec3& lab ):
m_l( lab[0] ),
m_a( lab[1] ),
m_b( lab[2] )
{
}
LabColor::LabColor( const kvs::LabColor& lab ):
m_l( lab.l() ),
m_a( lab.a() ),
m_b( lab.b() )
{
}
LabColor::LabColor( const kvs::XYZColor& xyz )
{
*this = ::XYZ2Lab( xyz );
}
kvs::XYZColor LabColor::toXYZColor() const
{
return ::Lab2XYZ( *this );
}
kvs::MshColor LabColor::toMshColor() const
{
return kvs::MshColor( *this );
}
kvs::LabColor& LabColor::operator += ( const kvs::LabColor& lab )
{
m_l += lab.l();
m_a += lab.a();
m_b += lab.b();
return *this;
}
kvs::LabColor& LabColor::operator -= ( const kvs::LabColor& lab )
{
m_l -= lab.l();
m_a -= lab.a();
m_b -= lab.b();
return *this;
}
kvs::LabColor& LabColor::operator = ( const kvs::LabColor& lab )
{
m_l = lab.l();
m_a = lab.a();
m_b = lab.b();
return *this;
}
kvs::LabColor& LabColor::operator = ( const kvs::XYZColor& xyz )
{
*this = ::XYZ2Lab( xyz );
return *this;
}
kvs::LabColor operator + ( const kvs::LabColor& a, const kvs::LabColor& b )
{
kvs::LabColor ret( a ); ret += b;
return ret;
}
bool operator == ( const kvs::LabColor& a, const kvs::LabColor& b )
{
return
kvs::Math::Equal( a.l(), b.l() ) &&
kvs::Math::Equal( a.a(), b.a() ) &&
kvs::Math::Equal( a.b(), b.b() );
}
} // end of namespace kvs
<commit_msg>modified.<commit_after>/*****************************************************************************/
/**
* @file LabColor.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id$
*/
/*****************************************************************************/
#include "LabColor.h"
#include "XYZColor.h"
#include "MshColor.h"
namespace
{
//const kvs::Vec3 ReferenceWhite( 1.0, 1.0, 1.0 );
//const kvs::Vec3 ReferenceWhite( 0.964221, 1.0, 0.825211 ); // D50
const kvs::Vec3 ReferenceWhite( 0.95047, 1.0, 1.08883 ); // D65
kvs::Real32 f( const kvs::Real32 t )
{
if ( t > 0.008856 ) { return std::pow( t, 1.0f / 3.0f ); }
else { return 7.787037 * t + 16.0 / 116.0; }
}
kvs::Real32 finv( const kvs::Real32 t )
{
if ( t > 0.008856 ) { return std::pow( t, 3.0f ); }
else { return ( t - 16.0 / 116.0 ) / 7.787037; }
}
kvs::LabColor XYZ2Lab( const kvs::XYZColor& xyz )
{
const kvs::Real32 Xn = ReferenceWhite.x();
const kvs::Real32 Yn = ReferenceWhite.y();
const kvs::Real32 Zn = ReferenceWhite.z();
const kvs::Real32 X = xyz.x();
const kvs::Real32 Y = xyz.y();
const kvs::Real32 Z = xyz.z();
const kvs::Real32 l = 116.0 * ( f( Y / Yn ) - 16.0 / 116.0 );
const kvs::Real32 a = 500.0 * ( f( X / Xn ) - f( Y / Yn ) );
const kvs::Real32 b = 200.0 * ( f( Y / Yn ) - f( Z / Zn ) );
return kvs::LabColor( l, a, b );
}
kvs::XYZColor Lab2XYZ( const kvs::LabColor& lab )
{
const kvs::Real32 Xn = ReferenceWhite.x();
const kvs::Real32 Yn = ReferenceWhite.y();
const kvs::Real32 Zn = ReferenceWhite.z();
const kvs::Real32 l = lab.l();
const kvs::Real32 a = lab.a();
const kvs::Real32 b = lab.b();
const kvs::Real32 y = ( l + 16.0 ) / 116.0;
const kvs::Real32 x = a / 500.0 + y;
const kvs::Real32 z = y - b / 200.0;
const kvs::Real32 X = Xn * finv( x );
const kvs::Real32 Y = Yn * finv( y );
const kvs::Real32 Z = Zn * finv( z );
return kvs::XYZColor( X, Y, Z );
}
}
namespace kvs
{
LabColor::LabColor( kvs::Real32 l, kvs::Real32 a, kvs::Real32 b ):
m_l( l ),
m_a( a ),
m_b( b )
{
}
LabColor::LabColor( const kvs::Vec3& lab ):
m_l( lab[0] ),
m_a( lab[1] ),
m_b( lab[2] )
{
}
LabColor::LabColor( const kvs::LabColor& lab ):
m_l( lab.l() ),
m_a( lab.a() ),
m_b( lab.b() )
{
}
LabColor::LabColor( const kvs::XYZColor& xyz )
{
*this = ::XYZ2Lab( xyz );
}
kvs::XYZColor LabColor::toXYZColor() const
{
return ::Lab2XYZ( *this );
}
kvs::MshColor LabColor::toMshColor() const
{
return kvs::MshColor( *this );
}
kvs::LabColor& LabColor::operator += ( const kvs::LabColor& lab )
{
m_l += lab.l();
m_a += lab.a();
m_b += lab.b();
return *this;
}
kvs::LabColor& LabColor::operator -= ( const kvs::LabColor& lab )
{
m_l -= lab.l();
m_a -= lab.a();
m_b -= lab.b();
return *this;
}
kvs::LabColor& LabColor::operator = ( const kvs::LabColor& lab )
{
m_l = lab.l();
m_a = lab.a();
m_b = lab.b();
return *this;
}
kvs::LabColor& LabColor::operator = ( const kvs::XYZColor& xyz )
{
*this = ::XYZ2Lab( xyz );
return *this;
}
kvs::LabColor operator + ( const kvs::LabColor& a, const kvs::LabColor& b )
{
kvs::LabColor ret( a ); ret += b;
return ret;
}
bool operator == ( const kvs::LabColor& a, const kvs::LabColor& b )
{
return
kvs::Math::Equal( a.l(), b.l() ) &&
kvs::Math::Equal( a.a(), b.a() ) &&
kvs::Math::Equal( a.b(), b.b() );
}
} // end of namespace kvs
<|endoftext|>
|
<commit_before>/*
bonjouraccount.cpp - Kopete Bonjour Protocol
Copyright (c) 2007 by Tejas Dinkar <tejas@gja.in>
Copyright (c) 2003 by Will Stephenson <will@stevello.free-online.co.uk>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library 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. *
* *
*************************************************************************
*/
#include <QtDBus>
#include <kaction.h>
#include <kdebug.h>
#include <klocale.h>
#include <kactionmenu.h>
#include <kmenu.h>
#include <kicon.h>
#include <dnssd/publicservice.h>
#include "kopetemetacontact.h"
#include "kopetecontactlist.h"
#include "kopetedeletecontacttask.h"
#include "bonjouraccount.h"
#include "bonjourcontact.h"
#include "bonjourfakeserver.h"
#include "bonjourprotocol.h"
#include "bonjourcontactconnection.h"
BonjourAccount::BonjourAccount( BonjourProtocol *parent, const QString& accountID )
: Kopete::Account ( parent, accountID )
{
// Init the myself contact
setMyself( new BonjourContact( this, accountId(), accountId(), Kopete::ContactList::self()->myself() ) );
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourOffline );
m_server = new BonjourFakeServer();;
service = NULL;
localServer = NULL;
listeningPort = 0;
browser = NULL;
// All Contacts Go To The Bonjour Group
bonjourGroup = Kopete::ContactList::self()->findGroup("Bonjour");
// Clean out Contacts from last time when kopete starts up
wipeOutAllContacts();
}
BonjourAccount::~BonjourAccount()
{
if (isConnected())
disconnect();
delete m_server;
}
KActionMenu* BonjourAccount::actionMenu()
{
KActionMenu *mActionMenu = Kopete::Account::actionMenu();
mActionMenu->addSeparator();
KAction *action;
action = new KAction (KIcon("bonjour_showvideo"), i18n ("Show my own video..."), mActionMenu );
//, "actionShowVideo");
QObject::connect( action, SIGNAL(triggered(bool)), this, SLOT(slotShowVideo()) );
mActionMenu->addAction(action);
action->setEnabled( isConnected() );
return mActionMenu;
}
bool BonjourAccount::createContact(const QString& contactId, Kopete::MetaContact* parentContact)
{
BonjourContact* newContact = new BonjourContact( this, contactId, parentContact->displayName(), parentContact );
return newContact != 0L;
}
void BonjourAccount::setAway( bool away, const QString & /* reason */ )
{
if ( away )
slotGoAway();
else
slotGoOnline();
}
void BonjourAccount::setOnlineStatus(const Kopete::OnlineStatus& status, const Kopete::StatusMessage &reason )
{
if ( status.status() == Kopete::OnlineStatus::Online &&
myself()->onlineStatus().status() == Kopete::OnlineStatus::Offline )
slotGoOnline();
else if (status.status() == Kopete::OnlineStatus::Online &&
myself()->onlineStatus().status() == Kopete::OnlineStatus::Away )
setAway( false, reason.message() );
else if ( status.status() == Kopete::OnlineStatus::Offline )
slotGoOffline();
else if ( status.status() == Kopete::OnlineStatus::Away )
slotGoAway( /* reason */ );
}
void BonjourAccount::setStatusMessage(const Kopete::StatusMessage& statusMessage)
{
Q_UNUSED(statusMessage);
/* Not used in bonjour */
}
// This Function Starts a new Local Server
// It runs on local port listeningPort
// Make Sure IP Tables lets this port through!!
bool BonjourAccount::startLocalServer()
{
int port = 5298;
localServer = new QTcpServer();
while (port < 5305) // No of Attempts
if (localServer->listen(QHostAddress::Any, port)) {
QObject::connect(localServer, SIGNAL(newConnection()),
this, SLOT(newIncomingConnection()));
listeningPort = port;
break;
}
else
port++;
return localServer->isListening();
}
void BonjourAccount::startBrowse()
{
// Delete All Contacts Before we start looking for new ones
wipeOutAllContacts();
browser = new DNSSD::ServiceBrowser("_presence._tcp");
QObject::connect(browser,SIGNAL(serviceAdded(DNSSD::RemoteService::Ptr)),
this,SLOT(comingOnline(DNSSD::RemoteService::Ptr)));
QObject::connect(browser,SIGNAL(serviceRemoved(DNSSD::RemoteService::Ptr)),
this,SLOT(goingOffline(DNSSD::RemoteService::Ptr)));
browser->startBrowse();
}
void BonjourAccount::startPublish()
{
if (! fullName.contains('@')) {
fullName.append("@");
fullName.append(getLocalHostName().toUtf8());
}
service = new DNSSD::PublicService(fullName, "_presence._tcp", listeningPort);
QMap <QString, QByteArray> map;
map.insert("1st", firstName);
map.insert("email", emailAddress);
map.insert("last", lastName);
map.insert("node", "kopete");
map.insert("port.p2pj", QByteArray::number(listeningPort)); // This Number Actuall Ignored
map.insert("status", "avail");
map.insert("txtvers", "1");
map.insert("vc", "!");
map.insert("ver", "0.0.1");
service->setTextData(map);
service->publish();
}
void BonjourAccount::connect( const Kopete::OnlineStatus& /* initialStatus */ )
{
if (fullName.isEmpty())
fullName = accountId().toUtf8();
if (! startLocalServer())
return;
startPublish();
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourOnline );
startBrowse();
QObject::connect ( m_server, SIGNAL ( messageReceived( const QString & ) ),
this, SLOT ( receivedMessage( const QString & ) ) );
}
void BonjourAccount::comingOnline(DNSSD::RemoteService::Ptr pointer)
{
pointer->resolve();
kDebug()<<"\nComing Online\n";
if (pointer->serviceName() == fullName) // Don't Add Ourselves
return;
QString display = pointer->serviceName().split("@")[0];
Kopete::MetaContact *mc;
// FIXME: The Standard Has Specifications on What To Do in case of a clash
// We Ignore them over here.
mc = addContact(pointer->serviceName(), display, bonjourGroup);
Kopete::Contact *c = mc->contacts()[0];
//FIXME: QObject is needed to be called here as there is a conflict fo setproperty
c->QObject::setProperty("remoteHostName", pointer->hostName());
c->QObject::setProperty("remotePort", pointer->port());
c->setOnlineStatus(Kopete::OnlineStatus::Online);
}
void BonjourAccount::goingOffline(DNSSD::RemoteService::Ptr pointer)
{
pointer->resolve();
Kopete::Contact *c = contacts()[pointer->serviceName()];
wipeOutContact(c);
}
void BonjourAccount::wipeOutContact(Kopete::Contact *c)
{
if (c == myself())
return;
Kopete::MetaContact *mc = c->metaContact();
c->setOnlineStatus(Kopete::OnlineStatus::Offline);
mc->removeContact(c);
// FIXME: DeleteContact task should be extended and used
Kopete::DeleteContactTask task(c);
task.start();
if (mc->contacts().isEmpty())
Kopete::ContactList::self()->removeMetaContact(mc);
}
void BonjourAccount::wipeOutAllContacts()
{
QList <Kopete::Contact *> list = contacts().values();
for (QList <Kopete::Contact *>::Iterator i = list.begin(); i != list.end(); i++)
wipeOutContact(*i);
}
void BonjourAccount::disconnect()
{
wipeOutAllContacts();
localServer->close();
service->stop();
delete browser;
browser = NULL;
delete localServer;
localServer = NULL;
listeningPort = 0;
delete service;
service = NULL;
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourOffline );
QObject::disconnect ( m_server, 0, 0, 0 );
}
BonjourFakeServer * BonjourAccount::server()
{
return m_server;
}
void BonjourAccount::slotGoOnline ()
{
kDebug ( 14210 ) ;
if (!isConnected ())
connect ();
else
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourOnline );
updateContactStatus();
}
void BonjourAccount::slotGoAway ()
{
kDebug ( 14210 ) ;
if (!isConnected ())
connect();
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourAway );
updateContactStatus();
}
void BonjourAccount::slotGoOffline ()
{
kDebug ( 14210 ) ;
if (isConnected ())
disconnect ();
updateContactStatus();
}
void BonjourAccount::slotShowVideo ()
{
kDebug ( 14210 ) ;
if (isConnected ())
{
BonjourWebcamDialog *bonjourWebcamDialog = new BonjourWebcamDialog(0, 0);
Q_UNUSED(bonjourWebcamDialog);
}
updateContactStatus();
}
void BonjourAccount::receivedMessage( const QString &message )
{
// Look up the contact the message is from
QString from;
BonjourContact* messageSender;
from = message.section( ':', 0, 0 );
Kopete::Contact* contact = contacts()[from];
messageSender = dynamic_cast<BonjourContact *>( contact );
kDebug( 14210 ) << " got a message from " << from << ", " << messageSender << ", is: " << message;
// Pass it on to the contact to process and display via a KMM
if ( messageSender )
messageSender->receivedMessage( message );
else
kWarning(14210) << "unable to look up contact for delivery";
}
void BonjourAccount::updateContactStatus()
{
QHashIterator<QString, Kopete::Contact*>itr( contacts() );
for ( ; itr.hasNext(); ) {
itr.next();
itr.value()->setOnlineStatus( myself()->onlineStatus() );
}
}
void BonjourAccount::setfullName(const QByteArray &n_fullName)
{
fullName = n_fullName;
}
void BonjourAccount::setfirstName(const QByteArray &n_firstName)
{
firstName = n_firstName;
}
void BonjourAccount::setlastName(const QByteArray &n_lastName)
{
lastName = n_lastName;
}
void BonjourAccount::setemailAddress(const QByteArray &n_emailAddress)
{
emailAddress = n_emailAddress;
}
const QByteArray BonjourAccount::getfullName() const
{
return fullName;
}
const QByteArray BonjourAccount::getfirstName() const
{
return firstName;
}
const QByteArray BonjourAccount::getlastName() const
{
return lastName;
}
const QByteArray BonjourAccount::getemailAddress() const
{
return emailAddress;
}
QList <BonjourContact *> BonjourAccount::getContactsByAddress(const QHostAddress &addr)
{
QList <BonjourContact *> list;
QList <Kopete::Contact *> c = contacts().values();
for (QList <Kopete::Contact *>::iterator i = c.begin(); i != c.end(); i++) {
BonjourContact *c = (BonjourContact *) *i;
if (c->isRemoteAddress(addr))
list<<c;
}
return list;
}
void BonjourAccount::newIncomingConnection()
{
// Get Next Connection
QTcpSocket *sock = localServer->nextPendingConnection();
BonjourContactConnection *bcc = new BonjourContactConnection(sock);
QObject::connect(bcc, SIGNAL(discoveredUserName(BonjourContactConnection *, QString)),
this, SLOT(discoveredUserName(BonjourContactConnection *, QString)));;
unknownConnections << bcc;
}
void BonjourAccount::discoveredUserName(BonjourContactConnection *conn, QString user)
{
kDebug()<<"User Making Contact (unverified): "<<user;
BonjourContact *c;
if (! (c = verifyUser(conn, user))) {
kDebug()<<"Ignoring Unverified User: "<<user;
return;
}
kDebug()<<"User Verified: "<<user;
unknownConnections.remove(conn);
c->setConnection(conn);
}
BonjourContact *BonjourAccount::verifyUser(BonjourContactConnection *conn, QString user)
{
// First Check the User Exists
if (! contacts().keys().contains(user))
return NULL;
BonjourContact *c = (BonjourContact *) contacts()[user];
if (c->getremoteAddress() != conn->getHostAddress())
return NULL;
return c;
}
#include "bonjouraccount.moc"
<commit_msg>Changed Display name so that it shows <firstname> <lastname> and not 'nickname'<commit_after>/*
bonjouraccount.cpp - Kopete Bonjour Protocol
Copyright (c) 2007 by Tejas Dinkar <tejas@gja.in>
Copyright (c) 2003 by Will Stephenson <will@stevello.free-online.co.uk>
Kopete (c) 2002-2003 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library 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. *
* *
*************************************************************************
*/
#include <QtDBus>
#include <kaction.h>
#include <kdebug.h>
#include <klocale.h>
#include <kactionmenu.h>
#include <kmenu.h>
#include <kicon.h>
#include <dnssd/publicservice.h>
#include "kopetemetacontact.h"
#include "kopetecontactlist.h"
#include "kopetedeletecontacttask.h"
#include "bonjouraccount.h"
#include "bonjourcontact.h"
#include "bonjourfakeserver.h"
#include "bonjourprotocol.h"
#include "bonjourcontactconnection.h"
BonjourAccount::BonjourAccount( BonjourProtocol *parent, const QString& accountID )
: Kopete::Account ( parent, accountID )
{
// Init the myself contact
setMyself( new BonjourContact( this, accountId(), accountId(), Kopete::ContactList::self()->myself() ) );
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourOffline );
m_server = new BonjourFakeServer();;
service = NULL;
localServer = NULL;
listeningPort = 0;
browser = NULL;
// All Contacts Go To The Bonjour Group
bonjourGroup = Kopete::ContactList::self()->findGroup("Bonjour");
// Clean out Contacts from last time when kopete starts up
wipeOutAllContacts();
}
BonjourAccount::~BonjourAccount()
{
if (isConnected())
disconnect();
delete m_server;
}
KActionMenu* BonjourAccount::actionMenu()
{
KActionMenu *mActionMenu = Kopete::Account::actionMenu();
mActionMenu->addSeparator();
KAction *action;
action = new KAction (KIcon("bonjour_showvideo"), i18n ("Show my own video..."), mActionMenu );
//, "actionShowVideo");
QObject::connect( action, SIGNAL(triggered(bool)), this, SLOT(slotShowVideo()) );
mActionMenu->addAction(action);
action->setEnabled( isConnected() );
return mActionMenu;
}
bool BonjourAccount::createContact(const QString& contactId, Kopete::MetaContact* parentContact)
{
BonjourContact* newContact = new BonjourContact( this, contactId, parentContact->displayName(), parentContact );
return newContact != 0L;
}
void BonjourAccount::setAway( bool away, const QString & /* reason */ )
{
if ( away )
slotGoAway();
else
slotGoOnline();
}
void BonjourAccount::setOnlineStatus(const Kopete::OnlineStatus& status, const Kopete::StatusMessage &reason )
{
if ( status.status() == Kopete::OnlineStatus::Online &&
myself()->onlineStatus().status() == Kopete::OnlineStatus::Offline )
slotGoOnline();
else if (status.status() == Kopete::OnlineStatus::Online &&
myself()->onlineStatus().status() == Kopete::OnlineStatus::Away )
setAway( false, reason.message() );
else if ( status.status() == Kopete::OnlineStatus::Offline )
slotGoOffline();
else if ( status.status() == Kopete::OnlineStatus::Away )
slotGoAway( /* reason */ );
}
void BonjourAccount::setStatusMessage(const Kopete::StatusMessage& statusMessage)
{
Q_UNUSED(statusMessage);
/* Not used in bonjour */
}
// This Function Starts a new Local Server
// It runs on local port listeningPort
// Make Sure IP Tables lets this port through!!
bool BonjourAccount::startLocalServer()
{
int port = 5298;
localServer = new QTcpServer();
while (port < 5305) // No of Attempts
if (localServer->listen(QHostAddress::Any, port)) {
QObject::connect(localServer, SIGNAL(newConnection()),
this, SLOT(newIncomingConnection()));
listeningPort = port;
break;
}
else
port++;
kDebug()<<"Listening On Port: "<<listeningPort;
return localServer->isListening();
}
void BonjourAccount::startBrowse()
{
// Delete All Contacts Before we start looking for new ones
wipeOutAllContacts();
browser = new DNSSD::ServiceBrowser("_presence._tcp");
QObject::connect(browser,SIGNAL(serviceAdded(DNSSD::RemoteService::Ptr)),
this,SLOT(comingOnline(DNSSD::RemoteService::Ptr)));
QObject::connect(browser,SIGNAL(serviceRemoved(DNSSD::RemoteService::Ptr)),
this,SLOT(goingOffline(DNSSD::RemoteService::Ptr)));
kDebug()<<"Starting Browser";
browser->startBrowse();
}
void BonjourAccount::startPublish()
{
if (! fullName.contains('@')) {
fullName.append("@");
fullName.append(getLocalHostName().toUtf8());
}
service = new DNSSD::PublicService(fullName, "_presence._tcp", listeningPort);
QMap <QString, QByteArray> map;
map.insert("1st", firstName);
map.insert("email", emailAddress);
map.insert("last", lastName);
map.insert("node", "kopete");
map.insert("port.p2pj", QByteArray::number(listeningPort)); // This Number Actuall Ignored
map.insert("status", "avail");
map.insert("txtvers", "1");
map.insert("vc", "!");
map.insert("ver", "0.0.1");
service->setTextData(map);
kDebug()<<"Starting Publish";
service->publish();
}
void BonjourAccount::connect( const Kopete::OnlineStatus& /* initialStatus */ )
{
if (fullName.isEmpty())
fullName = accountId().toUtf8();
if (! startLocalServer())
return;
startPublish();
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourOnline );
startBrowse();
QObject::connect ( m_server, SIGNAL ( messageReceived( const QString & ) ),
this, SLOT ( receivedMessage( const QString & ) ) );
}
void BonjourAccount::comingOnline(DNSSD::RemoteService::Ptr pointer)
{
pointer->resolve();
kDebug()<<"\nComing Online\n";
if (pointer->serviceName() == fullName) // Don't Add Ourselves
return;
QMap <QString, QByteArray> map = pointer->textData();
QString cfirst = map["1st"];
QString clast = map["last"];
QString display;
if (cfirst != "" && clast != "")
display = cfirst + " " + clast;
else if (cfirst != "")
display = cfirst;
else if (clast != "")
display = clast;
else
display = pointer->serviceName().split("@")[0];
Kopete::MetaContact *mc;
// FIXME: The Standard Has Specifications on What To Do in case of a clash
// We Ignore them over here.
mc = addContact(pointer->serviceName(), display, bonjourGroup);
Kopete::Contact *c = mc->contacts()[0];
//FIXME: QObject is needed to be called here as there is a conflict fo setproperty
c->QObject::setProperty("remoteHostName", pointer->hostName());
c->QObject::setProperty("remotePort", pointer->port());
c->setOnlineStatus(Kopete::OnlineStatus::Online);
}
void BonjourAccount::goingOffline(DNSSD::RemoteService::Ptr pointer)
{
pointer->resolve();
Kopete::Contact *c = contacts()[pointer->serviceName()];
wipeOutContact(c);
}
void BonjourAccount::wipeOutContact(Kopete::Contact *c)
{
if (c == myself())
return;
Kopete::MetaContact *mc = c->metaContact();
c->setOnlineStatus(Kopete::OnlineStatus::Offline);
mc->removeContact(c);
// FIXME: DeleteContact task should be extended and used
Kopete::DeleteContactTask task(c);
task.start();
if (mc->contacts().isEmpty())
Kopete::ContactList::self()->removeMetaContact(mc);
}
void BonjourAccount::wipeOutAllContacts()
{
QList <Kopete::Contact *> list = contacts().values();
for (QList <Kopete::Contact *>::Iterator i = list.begin(); i != list.end(); i++)
wipeOutContact(*i);
}
void BonjourAccount::disconnect()
{
wipeOutAllContacts();
localServer->close();
service->stop();
delete browser;
browser = NULL;
delete localServer;
localServer = NULL;
listeningPort = 0;
delete service;
service = NULL;
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourOffline );
QObject::disconnect ( m_server, 0, 0, 0 );
}
BonjourFakeServer * BonjourAccount::server()
{
return m_server;
}
void BonjourAccount::slotGoOnline ()
{
kDebug ( 14210 ) ;
if (!isConnected ())
connect ();
else
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourOnline );
updateContactStatus();
}
void BonjourAccount::slotGoAway ()
{
kDebug ( 14210 ) ;
if (!isConnected ())
connect();
myself()->setOnlineStatus( BonjourProtocol::protocol()->bonjourAway );
updateContactStatus();
}
void BonjourAccount::slotGoOffline ()
{
kDebug ( 14210 ) ;
if (isConnected ())
disconnect ();
updateContactStatus();
}
void BonjourAccount::slotShowVideo ()
{
kDebug ( 14210 ) ;
if (isConnected ())
{
BonjourWebcamDialog *bonjourWebcamDialog = new BonjourWebcamDialog(0, 0);
Q_UNUSED(bonjourWebcamDialog);
}
updateContactStatus();
}
void BonjourAccount::receivedMessage( const QString &message )
{
// Look up the contact the message is from
QString from;
BonjourContact* messageSender;
from = message.section( ':', 0, 0 );
Kopete::Contact* contact = contacts()[from];
messageSender = dynamic_cast<BonjourContact *>( contact );
kDebug( 14210 ) << " got a message from " << from << ", " << messageSender << ", is: " << message;
// Pass it on to the contact to process and display via a KMM
if ( messageSender )
messageSender->receivedMessage( message );
else
kWarning(14210) << "unable to look up contact for delivery";
}
void BonjourAccount::updateContactStatus()
{
QHashIterator<QString, Kopete::Contact*>itr( contacts() );
for ( ; itr.hasNext(); ) {
itr.next();
itr.value()->setOnlineStatus( myself()->onlineStatus() );
}
}
void BonjourAccount::setfullName(const QByteArray &n_fullName)
{
fullName = n_fullName;
}
void BonjourAccount::setfirstName(const QByteArray &n_firstName)
{
firstName = n_firstName;
}
void BonjourAccount::setlastName(const QByteArray &n_lastName)
{
lastName = n_lastName;
}
void BonjourAccount::setemailAddress(const QByteArray &n_emailAddress)
{
emailAddress = n_emailAddress;
}
const QByteArray BonjourAccount::getfullName() const
{
return fullName;
}
const QByteArray BonjourAccount::getfirstName() const
{
return firstName;
}
const QByteArray BonjourAccount::getlastName() const
{
return lastName;
}
const QByteArray BonjourAccount::getemailAddress() const
{
return emailAddress;
}
QList <BonjourContact *> BonjourAccount::getContactsByAddress(const QHostAddress &addr)
{
QList <BonjourContact *> list;
QList <Kopete::Contact *> c = contacts().values();
for (QList <Kopete::Contact *>::iterator i = c.begin(); i != c.end(); i++) {
BonjourContact *c = (BonjourContact *) *i;
if (c->isRemoteAddress(addr))
list<<c;
}
return list;
}
void BonjourAccount::newIncomingConnection()
{
// Get Next Connection
QTcpSocket *sock = localServer->nextPendingConnection();
BonjourContactConnection *bcc = new BonjourContactConnection(sock);
QObject::connect(bcc, SIGNAL(discoveredUserName(BonjourContactConnection *, QString)),
this, SLOT(discoveredUserName(BonjourContactConnection *, QString)));;
unknownConnections << bcc;
}
void BonjourAccount::discoveredUserName(BonjourContactConnection *conn, QString user)
{
kDebug()<<"User Making Contact (unverified): "<<user;
BonjourContact *c;
if (! (c = verifyUser(conn, user))) {
kDebug()<<"Ignoring Unverified User: "<<user;
return;
}
kDebug()<<"User Verified: "<<user;
unknownConnections.removeAll(conn);
c->setConnection(conn);
}
BonjourContact *BonjourAccount::verifyUser(BonjourContactConnection *conn, QString user)
{
// First Check the User Exists
if (! contacts().keys().contains(user))
return NULL;
BonjourContact *c = (BonjourContact *) contacts()[user];
if (c->getremoteAddress() != conn->getHostAddress())
return NULL;
return c;
}
#include "bonjouraccount.moc"
<|endoftext|>
|
<commit_before> /*
Copyright (c) 2006 by Olivier Goffart <ogoffart at kde.org>
Kopete (c) 2006 by the Kopete developers <kopete-devel@kde.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. *
* *
*************************************************************************
*/
#include "jabbertransport.h"
#include "jabbercontact.h"
#include "jabberaccount.h"
#include "jabberprotocol.h"
#include "jabbercontactpool.h"
#include <kopeteaccountmanager.h>
#include <kopetecontact.h>
#include <kopetecontactlist.h>
#include <kopeteversion.h>
#include <qpixmap.h>
#include <qtimer.h>
#include <kaction.h>
#include <kdebug.h>
#include <klocale.h>
#include <kconfig.h>
#include "xmpp_tasks.h"
JabberTransport::JabberTransport (JabberAccount * parentAccount, const QString & myselfContactId, const QString& gateway_type)
:Kopete::Account ( parentAccount->protocol(), myselfContactId+"/"+parentAccount->accountId())
{
m_status=Creating;
m_account = parentAccount;
m_account->addTransport( this, myselfContactId );
JabberContact *myContact = m_account->contactPool()->addContact ( XMPP::RosterItem ( myselfContactId ), Kopete::ContactList::self()->myself(), false );
setMyself( myContact );
//we have to know if the account get loaded from the config, or newly created
bool exist=configGroup()->readBoolEntry("exist",false);
if(!exist)
{
setColor( account()->color() );
#if KOPETE_IS_VERSION(0,11,51)
QString cIcon;
if(gateway_type=="msn")
cIcon="msn_protocol";
else if(gateway_type=="icq")
cIcon="icq_protocol";
else if(gateway_type=="aim")
cIcon="aim_protocol";
else if(gateway_type=="yahoo")
cIcon="yahoo_protocol";
else if(gateway_type=="sms")
cIcon="sms_protocol";
else if(gateway_type=="gadu-gadu")
cIcon="gadu_protocol";
else if(gateway_type=="smtp")
cIcon="mail_generic";
//TODO: theses gateway are referenced in http://www.jabber.org/registrar/disco-categories.html#gateway
// but i don't have icon now
/* else if(gateway_type=="http-ws")
cIcon="";
else if(gateway_type=="qq")
cIcon="";
else if(gateway_type=="tlen")
cIcon="";*/
else if(gateway_type=="irc") //NOTE: this is not official
cIcon="irc_protocol";
if( !cIcon.isEmpty() )
setCustomIcon( cIcon );
configGroup()->writeEntry("exist",true);
#endif
QTimer::singleShot(0, this, SLOT(eatContacts()));
}
m_status=Normal;
}
JabberTransport::~JabberTransport ()
{
m_account->removeTransport( myself()->contactId() );
}
KActionMenu *JabberTransport::actionMenu ()
{
KActionMenu *menu = new KActionMenu( accountId(), myself()->onlineStatus().iconFor( this ), this );
QString nick = myself()->property( Kopete::Global::Properties::self()->nickName()).value().toString();
menu->popupMenu()->insertTitle( myself()->onlineStatus().iconFor( myself() ),
nick.isNull() ? accountLabel() : i18n( "%2 <%1>" ).arg( accountLabel(), nick )
);
QPtrList<KAction> *customActions = myself()->customContextMenuActions( );
if( customActions && !customActions->isEmpty() )
{
menu->popupMenu()->insertSeparator();
for( KAction *a = customActions->first(); a; a = customActions->next() )
a->plug( menu->popupMenu() );
}
delete customActions;
return menu;
/* KActionMenu *m_actionMenu = Kopete::Account::actionMenu();
m_actionMenu->popupMenu()->insertSeparator();
m_actionMenu->insert(new KAction (i18n ("Join Groupchat..."), "jabber_group", 0,
this, SLOT (slotJoinNewChat ()), this, "actionJoinChat"));
m_actionMenu->popupMenu()->insertSeparator();
m_actionMenu->insert ( new KAction ( i18n ("Services..."), "jabber_serv_on", 0,
this, SLOT ( slotGetServices () ), this, "actionJabberServices") );
m_actionMenu->insert ( new KAction ( i18n ("Send Raw Packet to Server..."), "mail_new", 0,
this, SLOT ( slotSendRaw () ), this, "actionJabberSendRaw") );
m_actionMenu->insert ( new KAction ( i18n ("Edit User Info..."), "identity", 0,
this, SLOT ( slotEditVCard () ), this, "actionEditVCard") );
return m_actionMenu;*/
}
bool JabberTransport::createContact (const QString & contactId, Kopete::MetaContact * metaContact)
{
#if 0 //TODO
// collect all group names
QStringList groupNames;
Kopete::GroupList groupList = metaContact->groups();
for(Kopete::Group *group = groupList.first(); group; group = groupList.next())
groupNames += group->displayName();
XMPP::Jid jid ( contactId );
XMPP::RosterItem item ( jid );
item.setName ( metaContact->displayName () );
item.setGroups ( groupNames );
// this contact will be created with the "dirty" flag set
// (it will get reset if the contact appears in the roster during connect)
JabberContact *contact = contactPool()->addContact ( item, metaContact, true );
return ( contact != 0 );
#endif
return false;
}
void JabberTransport::setOnlineStatus( const Kopete::OnlineStatus& status , const QString &reason)
{
#if 0
if( status.status() == Kopete::OnlineStatus::Offline )
{
disconnect( Kopete::Account::Manual );
return;
}
if( isConnecting () )
{
errorConnectionInProgress ();
return;
}
XMPP::Status xmppStatus ( "", reason );
switch ( status.internalStatus () )
{
case JabberProtocol::JabberFreeForChat:
xmppStatus.setShow ( "chat" );
break;
case JabberProtocol::JabberOnline:
xmppStatus.setShow ( "" );
break;
case JabberProtocol::JabberAway:
xmppStatus.setShow ( "away" );
break;
case JabberProtocol::JabberXA:
xmppStatus.setShow ( "xa" );
break;
case JabberProtocol::JabberDND:
xmppStatus.setShow ( "dnd" );
break;
case JabberProtocol::JabberInvisible:
xmppStatus.setIsInvisible ( true );
break;
}
if ( !isConnected () )
{
// we are not connected yet, so connect now
m_initialPresence = xmppStatus;
connect ();
}
else
{
setPresence ( xmppStatus );
}
#endif
}
JabberProtocol * JabberTransport::protocol( ) const
{
return m_account->protocol();
}
bool JabberTransport::removeAccount( )
{
if(m_status == Removing || m_status == AccountRemoved)
return true; //so it can be deleted
if (!account()->isConnected())
{
account()->errorConnectFirst ();
return false;
}
m_status = Removing;
XMPP::JT_Register *task = new XMPP::JT_Register ( m_account->client()->rootTask () );
QObject::connect ( task, SIGNAL ( finished () ), this, SLOT ( removeAllContacts() ) );
//JabberContact *my=static_cast<JabberContact*>(myself());
task->unreg ( myself()->contactId() );
task->go ( true );
return false; //delay the removal
}
void JabberTransport::removeAllContacts( )
{
// XMPP::JT_Register * task = (XMPP::JT_Register *) sender ();
/* if ( ! task->success ())
KMessageBox::queuedMessageBox ( 0L, KMessageBox::Error,
i18n ("An error occured when trying to remove the transport:\n%1").arg(task->statusString()),
i18n ("Jabber Service Unregistration"));
*/ //we don't really care, we remove everithing anyway.
kdDebug() << k_funcinfo << "delete all contacts of the transport"<< endl;
QDictIterator<Kopete::Contact> it( contacts() );
for( ; it.current(); ++it )
{
XMPP::JT_Roster * rosterTask = new XMPP::JT_Roster ( account()->client()->rootTask () );
rosterTask->remove ( static_cast<JabberBaseContact*>(it.current())->rosterItem().jid() );
rosterTask->go ( true );
}
m_status = Removing; //in theory that's already our status
Kopete::AccountManager::self()->removeAccount( this ); //this will delete this
}
QString JabberTransport::legacyId( const XMPP::Jid & jid )
{
if(jid.node().isEmpty())
return QString();
QString node = jid.node();
return node.replace("%","@");
}
void JabberTransport::jabberAccountRemoved( )
{
m_status = AccountRemoved;
Kopete::AccountManager::self()->removeAccount( this ); //this will delete this
}
void JabberTransport::eatContacts( )
{
/*
* "Gateway Contact Eating" (c)(r)(tm)(g)(o)(f)
* this comes directly from my mind into the kopete code.
* principe: - the transport is ungry
* - it will eat contacts which belong to him
* - the contact will die
* - a new contact will born, with the same caracteristic, but owned by the transport
* - Olivier 2006-01-17 -
*/
QDict<Kopete::Contact> cts=account()->contacts();
QDictIterator<Kopete::Contact> it( cts );
for( ; it.current(); ++it )
{
JabberContact *contact=dynamic_cast<JabberContact*>(it.current());
if( contact && !contact->transport() && contact->rosterItem().jid().domain() == myself()->contactId() && contact != account()->myself())
{
XMPP::RosterItem item=contact->rosterItem();
Kopete::MetaContact *mc=contact->metaContact();
delete *it;
account()->contactPool()->addContact( item , mc , false ); //not sure this is false;
}
}
}
#include "jabbertransport.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>SVN_SILENT spell fixors<commit_after> /*
Copyright (c) 2006 by Olivier Goffart <ogoffart at kde.org>
Kopete (c) 2006 by the Kopete developers <kopete-devel@kde.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. *
* *
*************************************************************************
*/
#include "jabbertransport.h"
#include "jabbercontact.h"
#include "jabberaccount.h"
#include "jabberprotocol.h"
#include "jabbercontactpool.h"
#include <kopeteaccountmanager.h>
#include <kopetecontact.h>
#include <kopetecontactlist.h>
#include <kopeteversion.h>
#include <qpixmap.h>
#include <qtimer.h>
#include <kaction.h>
#include <kdebug.h>
#include <klocale.h>
#include <kconfig.h>
#include "xmpp_tasks.h"
JabberTransport::JabberTransport (JabberAccount * parentAccount, const QString & myselfContactId, const QString& gateway_type)
:Kopete::Account ( parentAccount->protocol(), myselfContactId+"/"+parentAccount->accountId())
{
m_status=Creating;
m_account = parentAccount;
m_account->addTransport( this, myselfContactId );
JabberContact *myContact = m_account->contactPool()->addContact ( XMPP::RosterItem ( myselfContactId ), Kopete::ContactList::self()->myself(), false );
setMyself( myContact );
//we have to know if the account get loaded from the config, or newly created
bool exist=configGroup()->readBoolEntry("exist",false);
if(!exist)
{
setColor( account()->color() );
#if KOPETE_IS_VERSION(0,11,51)
QString cIcon;
if(gateway_type=="msn")
cIcon="msn_protocol";
else if(gateway_type=="icq")
cIcon="icq_protocol";
else if(gateway_type=="aim")
cIcon="aim_protocol";
else if(gateway_type=="yahoo")
cIcon="yahoo_protocol";
else if(gateway_type=="sms")
cIcon="sms_protocol";
else if(gateway_type=="gadu-gadu")
cIcon="gadu_protocol";
else if(gateway_type=="smtp")
cIcon="mail_generic";
//TODO: theses gateway are referenced in http://www.jabber.org/registrar/disco-categories.html#gateway
// but i don't have icon now
/* else if(gateway_type=="http-ws")
cIcon="";
else if(gateway_type=="qq")
cIcon="";
else if(gateway_type=="tlen")
cIcon="";*/
else if(gateway_type=="irc") //NOTE: this is not official
cIcon="irc_protocol";
if( !cIcon.isEmpty() )
setCustomIcon( cIcon );
configGroup()->writeEntry("exist",true);
#endif
QTimer::singleShot(0, this, SLOT(eatContacts()));
}
m_status=Normal;
}
JabberTransport::~JabberTransport ()
{
m_account->removeTransport( myself()->contactId() );
}
KActionMenu *JabberTransport::actionMenu ()
{
KActionMenu *menu = new KActionMenu( accountId(), myself()->onlineStatus().iconFor( this ), this );
QString nick = myself()->property( Kopete::Global::Properties::self()->nickName()).value().toString();
menu->popupMenu()->insertTitle( myself()->onlineStatus().iconFor( myself() ),
nick.isNull() ? accountLabel() : i18n( "%2 <%1>" ).arg( accountLabel(), nick )
);
QPtrList<KAction> *customActions = myself()->customContextMenuActions( );
if( customActions && !customActions->isEmpty() )
{
menu->popupMenu()->insertSeparator();
for( KAction *a = customActions->first(); a; a = customActions->next() )
a->plug( menu->popupMenu() );
}
delete customActions;
return menu;
/* KActionMenu *m_actionMenu = Kopete::Account::actionMenu();
m_actionMenu->popupMenu()->insertSeparator();
m_actionMenu->insert(new KAction (i18n ("Join Groupchat..."), "jabber_group", 0,
this, SLOT (slotJoinNewChat ()), this, "actionJoinChat"));
m_actionMenu->popupMenu()->insertSeparator();
m_actionMenu->insert ( new KAction ( i18n ("Services..."), "jabber_serv_on", 0,
this, SLOT ( slotGetServices () ), this, "actionJabberServices") );
m_actionMenu->insert ( new KAction ( i18n ("Send Raw Packet to Server..."), "mail_new", 0,
this, SLOT ( slotSendRaw () ), this, "actionJabberSendRaw") );
m_actionMenu->insert ( new KAction ( i18n ("Edit User Info..."), "identity", 0,
this, SLOT ( slotEditVCard () ), this, "actionEditVCard") );
return m_actionMenu;*/
}
bool JabberTransport::createContact (const QString & contactId, Kopete::MetaContact * metaContact)
{
#if 0 //TODO
// collect all group names
QStringList groupNames;
Kopete::GroupList groupList = metaContact->groups();
for(Kopete::Group *group = groupList.first(); group; group = groupList.next())
groupNames += group->displayName();
XMPP::Jid jid ( contactId );
XMPP::RosterItem item ( jid );
item.setName ( metaContact->displayName () );
item.setGroups ( groupNames );
// this contact will be created with the "dirty" flag set
// (it will get reset if the contact appears in the roster during connect)
JabberContact *contact = contactPool()->addContact ( item, metaContact, true );
return ( contact != 0 );
#endif
return false;
}
void JabberTransport::setOnlineStatus( const Kopete::OnlineStatus& status , const QString &reason)
{
#if 0
if( status.status() == Kopete::OnlineStatus::Offline )
{
disconnect( Kopete::Account::Manual );
return;
}
if( isConnecting () )
{
errorConnectionInProgress ();
return;
}
XMPP::Status xmppStatus ( "", reason );
switch ( status.internalStatus () )
{
case JabberProtocol::JabberFreeForChat:
xmppStatus.setShow ( "chat" );
break;
case JabberProtocol::JabberOnline:
xmppStatus.setShow ( "" );
break;
case JabberProtocol::JabberAway:
xmppStatus.setShow ( "away" );
break;
case JabberProtocol::JabberXA:
xmppStatus.setShow ( "xa" );
break;
case JabberProtocol::JabberDND:
xmppStatus.setShow ( "dnd" );
break;
case JabberProtocol::JabberInvisible:
xmppStatus.setIsInvisible ( true );
break;
}
if ( !isConnected () )
{
// we are not connected yet, so connect now
m_initialPresence = xmppStatus;
connect ();
}
else
{
setPresence ( xmppStatus );
}
#endif
}
JabberProtocol * JabberTransport::protocol( ) const
{
return m_account->protocol();
}
bool JabberTransport::removeAccount( )
{
if(m_status == Removing || m_status == AccountRemoved)
return true; //so it can be deleted
if (!account()->isConnected())
{
account()->errorConnectFirst ();
return false;
}
m_status = Removing;
XMPP::JT_Register *task = new XMPP::JT_Register ( m_account->client()->rootTask () );
QObject::connect ( task, SIGNAL ( finished () ), this, SLOT ( removeAllContacts() ) );
//JabberContact *my=static_cast<JabberContact*>(myself());
task->unreg ( myself()->contactId() );
task->go ( true );
return false; //delay the removal
}
void JabberTransport::removeAllContacts( )
{
// XMPP::JT_Register * task = (XMPP::JT_Register *) sender ();
/* if ( ! task->success ())
KMessageBox::queuedMessageBox ( 0L, KMessageBox::Error,
i18n ("An error occured when trying to remove the transport:\n%1").arg(task->statusString()),
i18n ("Jabber Service Unregistration"));
*/ //we don't really care, we remove everithing anyway.
kdDebug() << k_funcinfo << "delete all contacts of the transport"<< endl;
QDictIterator<Kopete::Contact> it( contacts() );
for( ; it.current(); ++it )
{
XMPP::JT_Roster * rosterTask = new XMPP::JT_Roster ( account()->client()->rootTask () );
rosterTask->remove ( static_cast<JabberBaseContact*>(it.current())->rosterItem().jid() );
rosterTask->go ( true );
}
m_status = Removing; //in theory that's already our status
Kopete::AccountManager::self()->removeAccount( this ); //this will delete this
}
QString JabberTransport::legacyId( const XMPP::Jid & jid )
{
if(jid.node().isEmpty())
return QString();
QString node = jid.node();
return node.replace("%","@");
}
void JabberTransport::jabberAccountRemoved( )
{
m_status = AccountRemoved;
Kopete::AccountManager::self()->removeAccount( this ); //this will delete this
}
void JabberTransport::eatContacts( )
{
/*
* "Gateway Contact Eating" (c)(r)(tm)(g)(o)(f)
* this comes directly from my mind into the kopete code.
* principle: - the transport is hungry
* - it will eat contacts which belong to him
* - the contact will die
* - a new contact will born, with the same characteristics, but owned by the transport
* - Olivier 2006-01-17 -
*/
QDict<Kopete::Contact> cts=account()->contacts();
QDictIterator<Kopete::Contact> it( cts );
for( ; it.current(); ++it )
{
JabberContact *contact=dynamic_cast<JabberContact*>(it.current());
if( contact && !contact->transport() && contact->rosterItem().jid().domain() == myself()->contactId() && contact != account()->myself())
{
XMPP::RosterItem item=contact->rosterItem();
Kopete::MetaContact *mc=contact->metaContact();
delete *it;
account()->contactPool()->addContact( item , mc , false ); //not sure this is false;
}
}
}
#include "jabbertransport.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|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.
*****************************************************************************/
#include <string>
#include "gtest/gtest.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/integration_tests/planning_test_base.h"
#include "modules/planning/planning.h"
namespace apollo {
namespace planning {
/**
* @class SunnyvaleLoopTest
* @brief This is an integration test that uses the sunnyvale_loop map.
*/
class SunnyvaleLoopTest : public PlanningTestBase {
public:
virtual void SetUp() {
FLAGS_map_dir = "modules/map/data/sunnyvale_loop";
FLAGS_test_data_dir = "modules/planning/testdata/sunnyvale_loop_test";
FLAGS_test_routing_response_file = "1_routing.pb.txt";
}
};
/*
* test stop for not-nudgable obstacle
* A cruise test case
*/
TEST_F(SunnyvaleLoopTest, cruise) {
std::string seq_num = "1";
FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt";
FLAGS_test_localization_file = seq_num + "_localization.pb.txt";
FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt";
PlanningTestBase::SetUp();
RUN_GOLDEN_TEST;
}
/*
* stop case to trigger QP ST failed to solve
*/
TEST_F(SunnyvaleLoopTest, stop) {
std::string seq_num = "2";
FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt";
FLAGS_test_localization_file = seq_num + "_localization.pb.txt";
FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt";
FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt";
PlanningTestBase::SetUp();
RUN_GOLDEN_TEST;
}
} // namespace planning
} // namespace apollo
<commit_msg>Planning: fixed a bug in integration test..<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.
*****************************************************************************/
#include <string>
#include "gtest/gtest.h"
#include "modules/common/configs/config_gflags.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/integration_tests/planning_test_base.h"
#include "modules/planning/planning.h"
namespace apollo {
namespace planning {
/**
* @class SunnyvaleLoopTest
* @brief This is an integration test that uses the sunnyvale_loop map.
*/
class SunnyvaleLoopTest : public PlanningTestBase {
public:
virtual void SetUp() {
FLAGS_map_dir = "modules/map/data/sunnyvale_loop";
FLAGS_test_data_dir = "modules/planning/testdata/sunnyvale_loop_test";
FLAGS_test_routing_response_file = "1_routing.pb.txt";
}
};
/*
* test stop for not-nudgable obstacle
* A cruise test case
*/
TEST_F(SunnyvaleLoopTest, cruise) {
std::string seq_num = "1";
FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt";
FLAGS_test_localization_file = seq_num + "_localization.pb.txt";
FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt";
PlanningTestBase::SetUp();
RUN_GOLDEN_TEST;
}
/*
* stop case to trigger QP ST failed to solve
*/
// TODO: fix this test.
TEST_F(SunnyvaleLoopTest, stop) {
std::string seq_num = "2";
FLAGS_test_prediction_file = seq_num + "_prediction.pb.txt";
FLAGS_test_localization_file = seq_num + "_localization.pb.txt";
FLAGS_test_chassis_file = seq_num + "_chassis.pb.txt";
FLAGS_test_routing_response_file = seq_num + "_routing.pb.txt";
PlanningTestBase::SetUp();
bool run_planning_success = RunPlanning("sunnyvale_stop", 0);
EXPECT_FALSE(run_planning_success);
}
} // namespace planning
} // namespace apollo
<|endoftext|>
|
<commit_before>/*
* Copyright 2014 Cloudius Systems
*/
#ifndef SSTRING_HH_
#define SSTRING_HH_
#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
#include <experimental/string_view>
template <typename char_type, typename size_type, size_type max_size>
class basic_sstring {
union contents {
struct external_type {
char* str;
size_type size;
int8_t pad;
} external;
struct internal_type {
char str[max_size];
int8_t size;
} internal;
static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
static_assert(max_size <= 127, "max_size too large");
} u;
bool is_internal() const noexcept {
return u.internal.size >= 0;
}
bool is_external() const noexcept {
return !is_internal();
}
const char* str() const {
return is_internal() ? u.internal.str : u.external.str;
}
char* str() {
return is_internal() ? u.internal.str : u.external.str;
}
public:
struct initialized_later {};
basic_sstring() noexcept {
u.internal.size = 0;
u.internal.str[0] = '\0';
}
basic_sstring(const basic_sstring& x) {
if (x.is_internal()) {
u.internal = x.u.internal;
} else {
u.internal.size = -1;
u.external.str = new char[x.u.external.size + 1];
std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
u.external.size = x.u.external.size;
}
}
basic_sstring(basic_sstring&& x) noexcept {
u = x.u;
x.u.internal.size = 0;
x.u.internal.str[0] = '\0';
}
basic_sstring(initialized_later, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
std::copy(x, x + size, u.internal.str);
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
std::copy(x, x + size, u.external.str);
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {}
basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
basic_sstring(const std::basic_string<char_type>& s)
: basic_sstring(s.data(), s.size()) {}
~basic_sstring() noexcept {
if (is_external()) {
delete[] u.external.str;
}
}
basic_sstring& operator=(const basic_sstring& x) {
basic_sstring tmp(x);
swap(tmp);
return *this;
}
basic_sstring& operator=(basic_sstring&& x) noexcept {
if (this != &x) {
swap(x);
x.reset();
}
return *this;
}
operator std::string() const {
return str();
}
size_t size() const noexcept {
return is_internal() ? u.internal.size : u.external.size;
}
bool empty() const noexcept {
return u.internal.size == 0;
}
void reset() noexcept {
if (is_external()) {
delete[] u.external.str;
}
u.internal.size = 0;
u.internal.str[0] = '\0';
}
void swap(basic_sstring& x) noexcept {
contents tmp;
tmp = x.u;
x.u = u;
u = tmp;
}
const char* c_str() const {
return str();
}
const char_type* begin() const { return str(); }
const char_type* end() const { return str() + size(); }
char_type* begin() { return str(); }
char_type* end() { return str() + size(); }
bool operator==(const basic_sstring& x) const {
return size() == x.size() && std::equal(begin(), end(), x.begin());
}
bool operator!=(const basic_sstring& x) const {
return !operator==(x);
}
basic_sstring operator+(const basic_sstring& x) const {
basic_sstring ret(initialized_later(), size() + x.size());
std::copy(begin(), end(), ret.begin());
std::copy(x.begin(), x.end(), ret.begin() + size());
return ret;
}
basic_sstring& operator+=(const basic_sstring& x) {
return *this = *this + x;
}
operator std::experimental::string_view() const {
return std::experimental::string_view(str(), size());
}
};
template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
basic_sstring<char_type, size_type, max_size>& y) noexcept
{
return x.swap(y);
}
template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
const basic_sstring<char_type, size_type, max_size>& s) {
return os.write(s.begin(), s.size());
}
namespace std {
template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
return std::hash<std::experimental::string_view>()(s);
}
};
}
using sstring = basic_sstring<char, uint32_t, 15>;
template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);
template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
char tmp[sizeof(value) * 3 + 3];
auto len = std::sprintf(tmp, fmt, value);
return sstring(tmp, len);
}
template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
return to_sstring_sprintf(value, "%d");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
return to_sstring_sprintf(value, "%u");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
return to_sstring_sprintf(value, "%ld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%llu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(const char* value, void* = nullptr) {
return string_type(value);
}
template <typename string_type = sstring>
inline
string_type to_sstring(sstring value, void* = nullptr) {
return value;
}
template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
bool first = true;
os << "{";
for (auto&& elem : v) {
if (!first) {
os << ", ";
} else {
first = false;
}
os << elem;
}
os << "}";
return os;
}
#endif /* SSTRING_HH_ */
<commit_msg>sstring: introduce make_sstring()<commit_after>/*
* Copyright 2014 Cloudius Systems
*/
#ifndef SSTRING_HH_
#define SSTRING_HH_
#include <stdint.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <stdexcept>
#include <initializer_list>
#include <iostream>
#include <functional>
#include <cstdio>
#include <experimental/string_view>
template <typename char_type, typename size_type, size_type max_size>
class basic_sstring {
union contents {
struct external_type {
char* str;
size_type size;
int8_t pad;
} external;
struct internal_type {
char str[max_size];
int8_t size;
} internal;
static_assert(sizeof(external_type) <= sizeof(internal_type), "max_size too small");
static_assert(max_size <= 127, "max_size too large");
} u;
bool is_internal() const noexcept {
return u.internal.size >= 0;
}
bool is_external() const noexcept {
return !is_internal();
}
const char* str() const {
return is_internal() ? u.internal.str : u.external.str;
}
char* str() {
return is_internal() ? u.internal.str : u.external.str;
}
public:
struct initialized_later {};
basic_sstring() noexcept {
u.internal.size = 0;
u.internal.str[0] = '\0';
}
basic_sstring(const basic_sstring& x) {
if (x.is_internal()) {
u.internal = x.u.internal;
} else {
u.internal.size = -1;
u.external.str = new char[x.u.external.size + 1];
std::copy(x.u.external.str, x.u.external.str + x.u.external.size + 1, u.external.str);
u.external.size = x.u.external.size;
}
}
basic_sstring(basic_sstring&& x) noexcept {
u = x.u;
x.u.internal.size = 0;
x.u.internal.str[0] = '\0';
}
basic_sstring(initialized_later, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x, size_t size) {
if (size_type(size) != size) {
throw std::overflow_error("sstring overflow");
}
if (size + 1 <= sizeof(u.internal.str)) {
std::copy(x, x + size, u.internal.str);
u.internal.str[size] = '\0';
u.internal.size = size;
} else {
u.internal.size = -1;
u.external.str = new char[size + 1];
u.external.size = size;
std::copy(x, x + size, u.external.str);
u.external.str[size] = '\0';
}
}
basic_sstring(const char_type* x) : basic_sstring(x, std::strlen(x)) {}
basic_sstring(std::basic_string<char_type>& x) : basic_sstring(x.c_str(), x.size()) {}
basic_sstring(std::initializer_list<char_type> x) : basic_sstring(x.begin(), x.end() - x.begin()) {}
basic_sstring(const char_type* b, const char_type* e) : basic_sstring(b, e - b) {}
basic_sstring(const std::basic_string<char_type>& s)
: basic_sstring(s.data(), s.size()) {}
~basic_sstring() noexcept {
if (is_external()) {
delete[] u.external.str;
}
}
basic_sstring& operator=(const basic_sstring& x) {
basic_sstring tmp(x);
swap(tmp);
return *this;
}
basic_sstring& operator=(basic_sstring&& x) noexcept {
if (this != &x) {
swap(x);
x.reset();
}
return *this;
}
operator std::string() const {
return str();
}
size_t size() const noexcept {
return is_internal() ? u.internal.size : u.external.size;
}
bool empty() const noexcept {
return u.internal.size == 0;
}
void reset() noexcept {
if (is_external()) {
delete[] u.external.str;
}
u.internal.size = 0;
u.internal.str[0] = '\0';
}
void swap(basic_sstring& x) noexcept {
contents tmp;
tmp = x.u;
x.u = u;
u = tmp;
}
const char* c_str() const {
return str();
}
const char_type* begin() const { return str(); }
const char_type* end() const { return str() + size(); }
char_type* begin() { return str(); }
char_type* end() { return str() + size(); }
bool operator==(const basic_sstring& x) const {
return size() == x.size() && std::equal(begin(), end(), x.begin());
}
bool operator!=(const basic_sstring& x) const {
return !operator==(x);
}
basic_sstring operator+(const basic_sstring& x) const {
basic_sstring ret(initialized_later(), size() + x.size());
std::copy(begin(), end(), ret.begin());
std::copy(x.begin(), x.end(), ret.begin() + size());
return ret;
}
basic_sstring& operator+=(const basic_sstring& x) {
return *this = *this + x;
}
operator std::experimental::string_view() const {
return std::experimental::string_view(str(), size());
}
};
template <size_t N>
static inline
size_t str_len(const char(&s)[N]) { return N - 1; }
template <size_t N>
static inline
const char* str_begin(const char(&s)[N]) { return s; }
template <size_t N>
static inline
const char* str_end(const char(&s)[N]) { return str_begin(s) + str_len(s); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_begin(const basic_sstring<char_type, size_type, max_size>& s) { return s.begin(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
const char_type* str_end(const basic_sstring<char_type, size_type, max_size>& s) { return s.end(); }
template <typename char_type, typename size_type, size_type max_size>
static inline
size_type str_len(const basic_sstring<char_type, size_type, max_size>& s) { return s.size(); }
template <typename First, typename Second, typename... Tail>
static inline
const size_t str_len(const First& first, const Second& second, const Tail&... tail) {
return str_len(first) + str_len(second, tail...);
}
template <typename char_type, typename size_type, size_type max_size>
inline
void swap(basic_sstring<char_type, size_type, max_size>& x,
basic_sstring<char_type, size_type, max_size>& y) noexcept
{
return x.swap(y);
}
template <typename char_type, typename size_type, size_type max_size, typename char_traits>
inline
std::basic_ostream<char_type, char_traits>&
operator<<(std::basic_ostream<char_type, char_traits>& os,
const basic_sstring<char_type, size_type, max_size>& s) {
return os.write(s.begin(), s.size());
}
namespace std {
template <typename char_type, typename size_type, size_type max_size>
struct hash<basic_sstring<char_type, size_type, max_size>> {
size_t operator()(const basic_sstring<char_type, size_type, max_size>& s) const {
return std::hash<std::experimental::string_view>()(s);
}
};
}
using sstring = basic_sstring<char, uint32_t, 15>;
static inline
char* copy_str_to(char* dst) {
return dst;
}
template <typename Head, typename... Tail>
static inline
char* copy_str_to(char* dst, const Head& head, const Tail&... tail) {
return copy_str_to(std::copy(str_begin(head), str_end(head), dst), tail...);
}
template <typename String = sstring, typename... Args>
static String make_sstring(Args&&... args)
{
String ret(sstring::initialized_later(), str_len(args...));
copy_str_to(ret.begin(), args...);
return ret;
}
template <typename T, typename String = sstring, typename for_enable_if = void*>
String to_sstring(T value, for_enable_if);
template <typename T>
inline
sstring to_sstring_sprintf(T value, const char* fmt) {
char tmp[sizeof(value) * 3 + 3];
auto len = std::sprintf(tmp, fmt, value);
return sstring(tmp, len);
}
template <typename string_type = sstring>
inline
string_type to_sstring(int value, void* = nullptr) {
return to_sstring_sprintf(value, "%d");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned value, void* = nullptr) {
return to_sstring_sprintf(value, "%u");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long value, void* = nullptr) {
return to_sstring_sprintf(value, "%ld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%lld");
}
template <typename string_type = sstring>
inline
string_type to_sstring(unsigned long long value, void* = nullptr) {
return to_sstring_sprintf(value, "%llu");
}
template <typename string_type = sstring>
inline
string_type to_sstring(const char* value, void* = nullptr) {
return string_type(value);
}
template <typename string_type = sstring>
inline
string_type to_sstring(sstring value, void* = nullptr) {
return value;
}
template <typename T>
inline
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
bool first = true;
os << "{";
for (auto&& elem : v) {
if (!first) {
os << ", ";
} else {
first = false;
}
os << elem;
}
os << "}";
return os;
}
#endif /* SSTRING_HH_ */
<|endoftext|>
|
<commit_before>//
// Licensed to Green Energy Corp (www.greenenergycorp.com) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Green Enery Corp licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#include <boost/test/unit_test.hpp>
#include <APL/Log.h>
#include <APLTestTools/LogTester.h>
#include <APLTestTools/MockPhysicalLayerAsync.h>
#include <APLTestTools/MockTimerSource.h>
#include <APLTestTools/TestHelpers.h>
#include <DNP3/VtoRouter.h>
#include <DNP3/VtoWriter.h>
using namespace std;
using namespace apl;
using namespace apl::dnp;
class RouterTestClass : LogTester
{
public:
RouterTestClass() :
LogTester(false),
phys(mLog.GetLogger(LEV_DEBUG, "phys")),
writer(100),
mts(),
router(mLog.GetLogger(LEV_DEBUG, "router"), 8, &writer, &phys, &mts)
{}
MockPhysicalLayerAsync phys;
VtoWriter writer;
MockTimerSource mts;
VtoRouter router;
};
BOOST_AUTO_TEST_SUITE(VtoRouterTests)
BOOST_AUTO_TEST_CASE(Construction)
{
RouterTestClass rtc;
}
BOOST_AUTO_TEST_CASE(StartsReadingAfterOpen)
{
RouterTestClass rtc;
rtc.router.Start();
BOOST_REQUIRE(rtc.phys.IsOpening());
rtc.phys.SignalOpenSuccess();
BOOST_REQUIRE(rtc.phys.IsReading());
}
BOOST_AUTO_TEST_SUITE_END()
/* vim: set ts=4 sw=4: */
<commit_msg>Fixed file permissions on TestVtoRouter.cpp. Bless you, Windows.<commit_after>//
// Licensed to Green Energy Corp (www.greenenergycorp.com) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Green Enery Corp licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#include <boost/test/unit_test.hpp>
#include <APL/Log.h>
#include <APLTestTools/LogTester.h>
#include <APLTestTools/MockPhysicalLayerAsync.h>
#include <APLTestTools/MockTimerSource.h>
#include <APLTestTools/TestHelpers.h>
#include <DNP3/VtoRouter.h>
#include <DNP3/VtoWriter.h>
using namespace std;
using namespace apl;
using namespace apl::dnp;
class RouterTestClass : LogTester
{
public:
RouterTestClass() :
LogTester(false),
phys(mLog.GetLogger(LEV_DEBUG, "phys")),
writer(100),
mts(),
router(mLog.GetLogger(LEV_DEBUG, "router"), 8, &writer, &phys, &mts)
{}
MockPhysicalLayerAsync phys;
VtoWriter writer;
MockTimerSource mts;
VtoRouter router;
};
BOOST_AUTO_TEST_SUITE(VtoRouterTests)
BOOST_AUTO_TEST_CASE(Construction)
{
RouterTestClass rtc;
}
BOOST_AUTO_TEST_CASE(StartsReadingAfterOpen)
{
RouterTestClass rtc;
rtc.router.Start();
BOOST_REQUIRE(rtc.phys.IsOpening());
rtc.phys.SignalOpenSuccess();
BOOST_REQUIRE(rtc.phys.IsReading());
}
BOOST_AUTO_TEST_SUITE_END()
/* vim: set ts=4 sw=4: */
<|endoftext|>
|
<commit_before>#ifndef __SIMFQT_SIMFQT_TYPES_HPP
#define __SIMFQT_SIMFQT_TYPES_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <vector>
#include <string>
// StdAir
#include <stdair/stdair_exceptions.hpp>
namespace SIMFQT {
// ///////// Exceptions ///////////
class FareFileParsingFailedException : public stdair::ParsingFileFailedException {
public:
/** Constructor. */
FareFileParsingFailedException (const std::string& iWhat)
: stdair::ParsingFileFailedException (iWhat) {}
};
class AirportPairNotFoundException : public stdair::ObjectNotFoundException {
public:
/** Constructor. */
AirportPairNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
class PosOrChannelNotFoundException : public stdair::ObjectNotFoundException {
public:
/** Constructor. */
PosOrChannelNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
class FlightDateNotFoundException : public stdair::ObjectNotFoundException {
public:
/** Constructor. */
FlightDateNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
class FlightTimeNotFoundException : public stdair::ObjectNotFoundException {
public:
/** Constructor. */
FlightTimeNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
class FeaturesNotFoundException : public stdair::ObjectNotFoundException {
public:
/** Constructor. */
FeaturesNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
class AirlineNotFoundException : public stdair::ObjectNotFoundException {
public:
/** Constructor. */
AirlineNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
class FareInputFileNotFoundException : public stdair::FileNotFoundException {
public:
/** Constructor. */
FareInputFileNotFoundException (const std::string& iWhat)
: stdair::FileNotFoundException (iWhat) {}
};
class QuotingException : public stdair::RootException {
};
// //////// Type definitions specific to SimFQT /////////
/** ID for the Fare Quote system. */
typedef unsigned int FareQuoteID_T;
}
#endif // __SIMFQT_SIMFQT_TYPES_HPP
<commit_msg>[Dev] Implemented, for DSim and SimCRS, the option of building the BOM tree either from parsing input files or from built-in samples.<commit_after>#ifndef __SIMFQT_SIMFQT_TYPES_HPP
#define __SIMFQT_SIMFQT_TYPES_HPP
// //////////////////////////////////////////////////////////////////////
// Import section
// //////////////////////////////////////////////////////////////////////
// STL
#include <vector>
#include <string>
// Boost
#include <boost/shared_ptr.hpp>
// StdAir
#include <stdair/stdair_exceptions.hpp>
namespace SIMFQT {
// Forward declarations
class SIMFQT_Service;
// ///////// Exceptions ///////////
/**
* The fare input file can not be parsed.
*/
class FareFileParsingFailedException
: public stdair::ParsingFileFailedException {
public:
/**
* Constructor.
*/
FareFileParsingFailedException (const std::string& iWhat)
: stdair::ParsingFileFailedException (iWhat) {}
};
/**
* The given airport pair can not be found.
*/
class AirportPairNotFoundException : public stdair::ObjectNotFoundException {
public:
/**
* Constructor.
*/
AirportPairNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
/**
* The given POS/channel can not be found.
*/
class PosOrChannelNotFoundException : public stdair::ObjectNotFoundException {
public:
/**
* Constructor.
*/
PosOrChannelNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
/**
* The departure date of the flight can not be found.
*/
class FlightDateNotFoundException : public stdair::ObjectNotFoundException {
public:
/**
* Constructor.
*/
FlightDateNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
/**
* The departure time of the flight can not be found.
*/
class FlightTimeNotFoundException : public stdair::ObjectNotFoundException {
public:
/**
* Constructor.
*/
FlightTimeNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
/**
* The fare features can not be found.
*/
class FeaturesNotFoundException : public stdair::ObjectNotFoundException {
public:
/**
* Constructor.
*/
FeaturesNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
/**
* The airline can not be found.
*/
class AirlineNotFoundException : public stdair::ObjectNotFoundException {
public:
/**
* Constructor.
*/
AirlineNotFoundException (const std::string& iWhat)
: stdair::ObjectNotFoundException (iWhat) {}
};
/**
* The fare input file can not be found.
*/
class FareInputFileNotFoundException : public stdair::FileNotFoundException {
public:
/**
* Constructor.
*/
FareInputFileNotFoundException (const std::string& iWhat)
: stdair::FileNotFoundException (iWhat) {}
};
/**
* The pricing operation fails.
*/
class QuotingException : public stdair::RootException {
};
// //////// Type definitions specific to SimFQT /////////
/**
* ID for the Fare Quote system.
*/
typedef unsigned int FareQuoteID_T;
/**
* (Smart) Pointer on the SimFQT service handler.
*/
typedef boost::shared_ptr<SIMFQT_Service> SIMFQT_ServicePtr_T;
}
#endif // __SIMFQT_SIMFQT_TYPES_HPP
<|endoftext|>
|
<commit_before>#include <cassert>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <boost/heap/fibonacci_heap.hpp>
struct Edge {
const int target;
const int cost;
Edge(int target, int cost) : target(target), cost(cost) {}
};
struct Vertex {
std::mutex mutex;
std::vector<Edge> edges;
void add_edge(int target, int cost) {
std::lock_guard<std::mutex> lock(mutex);
edges.emplace_back(target, cost);
}
};
struct DistInfo {
int v;
int cost = std::numeric_limits<int>::max();
int parent = -1;
bool operator<(const DistInfo& that) const {
return this->cost > that.cost;
}
};
struct FilePartition {
const int threads;
const ssize_t start, stop, diff, div, mod;
FilePartition(int threads, ssize_t start, ssize_t stop)
: threads(threads),
start(start),
stop(stop),
diff(stop - start),
div(diff / threads),
mod(diff % threads) {}
ssize_t operator[](ssize_t tid) const {
return start + div * tid + std::min(mod, tid);
}
};
struct IntFile {
std::ifstream ifs;
int c = ' ';
ssize_t g = 0;
IntFile(const char* filename) : ifs(filename) {}
operator bool() { return (bool)ifs; }
IntFile& operator>>(int& other) {
other = 0;
while (c == ' ' or c == '\n' or c == '\t') {
c = ifs.get();
++g;
}
while ('0' <= c and c <= '9') {
other *= 10;
other += c - '0';
c = ifs.get();
++g;
}
return *this;
}
void seekg(ssize_t pos) {
ifs.seekg(pos);
g = pos;
}
ssize_t tellg() { return g; }
void ignore(ssize_t, int chr) {
while (c != '\n' and c != EOF) {
++g;
c = ifs.get();
}
}
};
char* infile;
std::vector<Vertex> vertices;
void read_file(ssize_t from, ssize_t to) {
// printf("%ld %ld %ld %s\n", from, to, vertices.size(), infile);
IntFile fin(infile);
assert(fin);
fin.seekg(from);
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while (fin.tellg() < to) {
int u, v, cost;
fin >> u >> v >> cost;
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
--u;
--v;
// printf("%d %d %d\n", u, v, cost);
vertices.at(u).add_edge(v, cost);
vertices.at(v).add_edge(u, cost);
}
}
void sincelast(const char* message = 0) {
static auto last = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
std::cout << message
<< ((std::chrono::duration<double>)(now - last)).count()
<< std::endl;
last = now;
}
int main(int argc, char** argv) {
std::ios_base::sync_with_stdio(false);
assert(argc == 5);
auto num_threads = std::stoi(argv[1]);
assert(num_threads > 0);
infile = argv[2];
std::ifstream fin(argv[2]);
std::ofstream fout(argv[3]);
auto origin = std::stoi(argv[4]) - 1;
if (not fin) {
throw std::runtime_error("bad input file");
}
if (not fout) {
throw std::runtime_error("bad output file");
}
int num_vertices, num_edges;
fin >> num_vertices >> num_edges;
auto file_start = fin.tellg();
fin.seekg(0, std::ios_base::end);
auto file_end = fin.tellg();
FilePartition fp(num_threads, file_start, file_end);
vertices = std::vector<Vertex>(num_vertices);
std::vector<std::thread> rfthreads;
sincelast("init ");
for (int i = 0; i < num_threads; ++i) {
rfthreads.emplace_back(read_file, fp[i], fp[i + 1]);
}
for (auto& thread : rfthreads) {
thread.join();
}
sincelast("input ");
std::vector<DistInfo> distinfo(num_vertices);
distinfo[origin].cost = 0;
distinfo[origin].parent = origin;
using heap_t = boost::heap::fibonacci_heap<DistInfo>;
heap_t heap;
std::vector<heap_t::handle_type> handles;
handles.reserve(num_vertices);
for (int v = 0; v < num_vertices; ++v) {
distinfo[v].v = v;
handles.emplace_back(heap.push(distinfo[v]));
}
while (not heap.empty()) {
int v = heap.top().v;
heap.pop();
const auto& vertex = vertices[v];
const auto& di = distinfo[v];
for (const auto& edge : vertex.edges) {
auto& dst = distinfo[edge.target];
auto off = di.cost + edge.cost;
if (dst.cost > off) {
dst.cost = off;
dst.parent = v;
heap.increase(handles[edge.target], dst);
}
}
}
sincelast("compute ");
for (int i = 0; i < num_vertices; ++i) {
std::vector<int> path;
int cur = i;
path.push_back(cur + 1);
do {
cur = distinfo[cur].parent;
path.push_back(cur + 1);
} while (cur != origin);
std::copy(path.crbegin(), path.crend(),
std::ostream_iterator<int>(fout, " "));
fout << '\n';
}
sincelast("output ");
}
<commit_msg>fix a bug<commit_after>#include <cassert>
#include <fstream>
#include <iostream>
#include <iterator>
#include <limits>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <boost/heap/fibonacci_heap.hpp>
struct Edge {
const int target;
const int cost;
Edge(int target, int cost) : target(target), cost(cost) {}
};
struct Vertex {
std::mutex mutex;
std::vector<Edge> edges;
void add_edge(int target, int cost) {
std::lock_guard<std::mutex> lock(mutex);
edges.emplace_back(target, cost);
}
};
struct DistInfo {
int v;
int cost = std::numeric_limits<int>::max();
int parent = -1;
bool operator<(const DistInfo& that) const {
return this->cost > that.cost;
}
};
struct FilePartition {
const int threads;
const ssize_t start, stop, diff, div, mod;
FilePartition(int threads, ssize_t start, ssize_t stop)
: threads(threads),
start(start),
stop(stop),
diff(stop - start),
div(diff / threads),
mod(diff % threads) {}
ssize_t operator[](ssize_t tid) const {
return start + div * tid + std::min(mod, tid);
}
};
struct IntFile {
std::ifstream ifs;
int c = ' ';
ssize_t g = 0;
IntFile(const char* filename) : ifs(filename) {}
operator bool() { return (bool)ifs; }
IntFile& operator>>(int& other) {
other = 0;
while (c == ' ' or c == '\n' or c == '\t') {
c = ifs.get();
++g;
}
while ('0' <= c and c <= '9') {
other *= 10;
other += c - '0';
c = ifs.get();
++g;
}
return *this;
}
void seekg(ssize_t pos) {
ifs.seekg(pos);
g = pos;
}
ssize_t tellg() { return g; }
void ignore(ssize_t, int chr) {
while (c != '\n' and c != EOF) {
++g;
c = ifs.get();
}
}
};
char* infile;
std::vector<Vertex> vertices;
void read_file(ssize_t from, ssize_t to) {
// printf("%ld %ld %ld %s\n", from, to, vertices.size(), infile);
IntFile fin(infile);
assert(fin);
fin.seekg(from);
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
while (fin.tellg() < to) {
int u, v, cost;
fin >> u >> v >> cost;
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
--u;
--v;
// printf("%d %d %d\n", u, v, cost);
vertices.at(u).add_edge(v, cost);
vertices.at(v).add_edge(u, cost);
}
}
void sincelast(const char* message = 0) {
static auto last = std::chrono::high_resolution_clock::now();
auto now = std::chrono::high_resolution_clock::now();
std::cout << message
<< ((std::chrono::duration<double>)(now - last)).count()
<< std::endl;
last = now;
}
int main(int argc, char** argv) {
std::ios_base::sync_with_stdio(false);
assert(argc == 5);
auto num_threads = std::stoi(argv[1]);
assert(num_threads > 0);
infile = argv[2];
std::ifstream fin(argv[2]);
std::ofstream fout(argv[3]);
auto origin = std::stoi(argv[4]) - 1;
if (not fin) {
throw std::runtime_error("bad input file");
}
if (not fout) {
throw std::runtime_error("bad output file");
}
int num_vertices, num_edges;
fin >> num_vertices >> num_edges;
auto file_start = fin.tellg();
fin.seekg(0, std::ios_base::end);
auto file_end = fin.tellg();
FilePartition fp(num_threads, file_start, file_end);
vertices = std::vector<Vertex>(num_vertices);
std::vector<std::thread> rfthreads;
sincelast("init ");
for (int i = 0; i < num_threads; ++i) {
rfthreads.emplace_back(read_file, fp[i] - 1, fp[i + 1]);
}
for (auto& thread : rfthreads) {
thread.join();
}
sincelast("input ");
std::vector<DistInfo> distinfo(num_vertices);
distinfo[origin].cost = 0;
distinfo[origin].parent = origin;
using heap_t = boost::heap::fibonacci_heap<DistInfo>;
heap_t heap;
std::vector<heap_t::handle_type> handles;
handles.reserve(num_vertices);
for (int v = 0; v < num_vertices; ++v) {
distinfo[v].v = v;
handles.emplace_back(heap.push(distinfo[v]));
}
while (not heap.empty()) {
int v = heap.top().v;
heap.pop();
const auto& vertex = vertices[v];
const auto& di = distinfo[v];
for (const auto& edge : vertex.edges) {
auto& dst = distinfo[edge.target];
auto off = di.cost + edge.cost;
if (dst.cost > off) {
dst.cost = off;
dst.parent = v;
heap.increase(handles[edge.target], dst);
}
}
}
sincelast("compute ");
for (int i = 0; i < num_vertices; ++i) {
std::vector<int> path;
int cur = i;
path.push_back(cur + 1);
do {
cur = distinfo[cur].parent;
path.push_back(cur + 1);
} while (cur != origin);
std::copy(path.crbegin(), path.crend(),
std::ostream_iterator<int>(fout, " "));
fout << '\n';
}
sincelast("output ");
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2008-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#include "top.hpp"
#include "utils/flags.hpp"
#include <unordered_map>
#include <string>
#include <cstdlib>
#include <cstring>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#else
#include <unistd.h>
#endif // !_WIN32
namespace {
const char* removeQuotes(const char* Value) {
const char *b, *e, *p;
if (Value == NULL) {
return Value;
}
// skip the leading blank
for (p = Value; *p == ' '; ++p)
;
if (*p != '"') {
return Value;
}
b = p;
e = NULL;
for (++p; *p != '\0'; ++p) {
if (*p == '"') {
// e points to the last '"'
e = p;
} else if ((e != NULL) && (*p != ' ')) {
// e isn't last '"' if there is any non-blank following e
e = NULL;
}
}
if (e == NULL) {
return Value;
}
// Found a valid quoted string "<str>" with b=1st '"' and e=the last '"'
size_t len = (e - b - 1) > 0 ? (e - b - 1) : 0;
#ifdef _WIN32
char* p1 = _strdup(b + 1);
p1[len] = '\0';
p = p1;
#else
p = strndup(b + 1, len);
#endif
return p;
}
}
namespace amd {
#ifdef __APPLE__
#include <crt_externs.h>
#endif // __APPLE__
bool IS_HIP = false;
std::atomic_bool IS_PROFILER_ON(false);
#if defined(WITH_GPU_DEVICE)
bool IS_LEGACY = true;
#else
bool IS_LEGACY = false;
#endif
// static
char* Flag::envstr_;
void Flag::tearDown() {
#ifdef _WIN32
FreeEnvironmentStringsA(envstr_);
#endif
}
bool Flag::init() {
typedef std::unordered_map<std::string, const char*> vars_type;
vars_type vars;
#ifdef _WIN32
char* str = GetEnvironmentStringsA();
envstr_ = str;
for (; *str != '\0'; str += strlen(str) + 1) {
// For all environment variables:
std::string var = str;
size_t pos = var.find('=');
if ((pos == std::string::npos) || ((pos + 1) >= var.size())) {
continue;
}
std::string name = var.substr(0, pos);
vars.insert(std::make_pair(name, &str[pos + 1]));
}
#else // !_WIN32
#ifdef __APPLE__
char** environ = *_NSGetEnviron();
if (environ == NULL) {
return false;
}
#endif // __APPLE__
for (const char** p = const_cast<const char**>(environ); *p != NULL; ++p) {
std::string var = *p;
size_t pos = var.find('=');
if ((pos == std::string::npos) || ((pos + 1) >= var.size())) {
continue;
}
std::string name = var.substr(0, pos);
vars.insert(std::make_pair(name, &(*p)[pos + 1]));
}
#endif // !_WIN32
for (size_t i = 0; i < numFlags_; ++i) {
Flag& flag = flags_[i];
const auto it = vars.find(flag.name_);
if (it != vars.cend()) {
flag.setValue(it->second);
}
}
if (!flagIsDefault(AMD_LOG_LEVEL)) {
if (!flagIsDefault(AMD_LOG_LEVEL_FILE)) {
std::string fileName = AMD_LOG_LEVEL_FILE;
outFile = fopen(fileName.c_str(), "w");
}
}
return true;
}
bool Flag::setValue(const char* value) {
if (value_ == NULL) {
return false; // flag is constant.
}
isDefault_ = false;
switch (type_) {
case Tbool:
*(bool*)value_ = (strcmp(value, "true") == 0 || atoi(value) != 0) ? true : false;
return true;
case Tint:
case Tuint:
*(int*)value_ = atoi(value);
return true;
case Tsize_t:
*(size_t*)value_ = atol(value);
return true;
case Tcstring:
*(const char**)value_ = removeQuotes(value);
return true;
default:
break;
}
ShouldNotReachHere();
return false;
}
#define DEFINE_RELEASE_FLAG_STRUCT(type, name, value, help) {#name, &name, T##type, true},
#define DEFINE_DEBUG_FLAG_STRUCT(type, name, value, help) \
{#name, RELEASE_ONLY(NULL) DEBUG_ONLY(&name), T##type, true},
Flag Flag::flags_[] = {
RUNTIME_FLAGS(DEFINE_DEBUG_FLAG_STRUCT, DEFINE_RELEASE_FLAG_STRUCT, DEFINE_DEBUG_FLAG_STRUCT)
{NULL, NULL, Tinvalid, true}};
#undef DEFINE_DEBUG_FLAG_STRUCT
#undef DEFINE_RELEASE_FLAG_STRUCT
} // namespace amd
#define DEFINE_RELEASE_FLAG_VALUE(type, name, value, help) type name = value;
#define DEFINE_DEBUG_FLAG_VALUE(type, name, value, help) DEBUG_ONLY(type name = value);
RUNTIME_FLAGS(DEFINE_DEBUG_FLAG_VALUE, DEFINE_RELEASE_FLAG_VALUE, DEFINE_DEBUG_FLAG_VALUE);
#undef DEFINE_DEBUG_FLAG_VALUE
#undef DEFINE_RELEASE_FLAG_VALUE
<commit_msg>SWDEV-86035 - Make sure the legacy lib is loaded with PAL backend<commit_after>/* Copyright (c) 2008-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#include "top.hpp"
#include "utils/flags.hpp"
#include <unordered_map>
#include <string>
#include <cstdlib>
#include <cstring>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#else
#include <unistd.h>
#endif // !_WIN32
namespace {
const char* removeQuotes(const char* Value) {
const char *b, *e, *p;
if (Value == NULL) {
return Value;
}
// skip the leading blank
for (p = Value; *p == ' '; ++p)
;
if (*p != '"') {
return Value;
}
b = p;
e = NULL;
for (++p; *p != '\0'; ++p) {
if (*p == '"') {
// e points to the last '"'
e = p;
} else if ((e != NULL) && (*p != ' ')) {
// e isn't last '"' if there is any non-blank following e
e = NULL;
}
}
if (e == NULL) {
return Value;
}
// Found a valid quoted string "<str>" with b=1st '"' and e=the last '"'
size_t len = (e - b - 1) > 0 ? (e - b - 1) : 0;
#ifdef _WIN32
char* p1 = _strdup(b + 1);
p1[len] = '\0';
p = p1;
#else
p = strndup(b + 1, len);
#endif
return p;
}
}
namespace amd {
#ifdef __APPLE__
#include <crt_externs.h>
#endif // __APPLE__
bool IS_HIP = false;
std::atomic_bool IS_PROFILER_ON(false);
#if defined(WITH_GPU_DEVICE)
bool IS_LEGACY = true;
#else
#if !defined(_WIN32) && defined(WITH_PAL_DEVICE)
bool IS_LEGACY = true;
#else
bool IS_LEGACY = false;
#endif
#endif
// static
char* Flag::envstr_;
void Flag::tearDown() {
#ifdef _WIN32
FreeEnvironmentStringsA(envstr_);
#endif
}
bool Flag::init() {
typedef std::unordered_map<std::string, const char*> vars_type;
vars_type vars;
#ifdef _WIN32
char* str = GetEnvironmentStringsA();
envstr_ = str;
for (; *str != '\0'; str += strlen(str) + 1) {
// For all environment variables:
std::string var = str;
size_t pos = var.find('=');
if ((pos == std::string::npos) || ((pos + 1) >= var.size())) {
continue;
}
std::string name = var.substr(0, pos);
vars.insert(std::make_pair(name, &str[pos + 1]));
}
#else // !_WIN32
#ifdef __APPLE__
char** environ = *_NSGetEnviron();
if (environ == NULL) {
return false;
}
#endif // __APPLE__
for (const char** p = const_cast<const char**>(environ); *p != NULL; ++p) {
std::string var = *p;
size_t pos = var.find('=');
if ((pos == std::string::npos) || ((pos + 1) >= var.size())) {
continue;
}
std::string name = var.substr(0, pos);
vars.insert(std::make_pair(name, &(*p)[pos + 1]));
}
#endif // !_WIN32
for (size_t i = 0; i < numFlags_; ++i) {
Flag& flag = flags_[i];
const auto it = vars.find(flag.name_);
if (it != vars.cend()) {
flag.setValue(it->second);
}
}
if (!flagIsDefault(AMD_LOG_LEVEL)) {
if (!flagIsDefault(AMD_LOG_LEVEL_FILE)) {
std::string fileName = AMD_LOG_LEVEL_FILE;
outFile = fopen(fileName.c_str(), "w");
}
}
return true;
}
bool Flag::setValue(const char* value) {
if (value_ == NULL) {
return false; // flag is constant.
}
isDefault_ = false;
switch (type_) {
case Tbool:
*(bool*)value_ = (strcmp(value, "true") == 0 || atoi(value) != 0) ? true : false;
return true;
case Tint:
case Tuint:
*(int*)value_ = atoi(value);
return true;
case Tsize_t:
*(size_t*)value_ = atol(value);
return true;
case Tcstring:
*(const char**)value_ = removeQuotes(value);
return true;
default:
break;
}
ShouldNotReachHere();
return false;
}
#define DEFINE_RELEASE_FLAG_STRUCT(type, name, value, help) {#name, &name, T##type, true},
#define DEFINE_DEBUG_FLAG_STRUCT(type, name, value, help) \
{#name, RELEASE_ONLY(NULL) DEBUG_ONLY(&name), T##type, true},
Flag Flag::flags_[] = {
RUNTIME_FLAGS(DEFINE_DEBUG_FLAG_STRUCT, DEFINE_RELEASE_FLAG_STRUCT, DEFINE_DEBUG_FLAG_STRUCT)
{NULL, NULL, Tinvalid, true}};
#undef DEFINE_DEBUG_FLAG_STRUCT
#undef DEFINE_RELEASE_FLAG_STRUCT
} // namespace amd
#define DEFINE_RELEASE_FLAG_VALUE(type, name, value, help) type name = value;
#define DEFINE_DEBUG_FLAG_VALUE(type, name, value, help) DEBUG_ONLY(type name = value);
RUNTIME_FLAGS(DEFINE_DEBUG_FLAG_VALUE, DEFINE_RELEASE_FLAG_VALUE, DEFINE_DEBUG_FLAG_VALUE);
#undef DEFINE_DEBUG_FLAG_VALUE
#undef DEFINE_RELEASE_FLAG_VALUE
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: global.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: hr $ $Date: 2006-06-20 04:09:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _RTL_OSTRINGBUFFER_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#include <stdlib.h>
#include <stdio.h>
#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif
#ifdef UNX
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif
#ifndef _CODEMAKER_GLOBAL_HXX_
#include <codemaker/global.hxx>
#endif
#ifdef SAL_UNX
#define SEPARATOR '/'
#else
#define SEPARATOR '\\'
#endif
using namespace ::rtl;
using namespace ::osl;
OString createFileNameFromType( const OString& destination,
const OString typeName,
const OString postfix,
sal_Bool bLowerCase,
const OString prefix )
{
OString type(typeName);
if (bLowerCase)
{
type = typeName.toAsciiLowerCase();
}
sal_uInt32 length = destination.getLength();
sal_Bool withPoint = sal_False;
if (length == 0)
{
length++;
withPoint = sal_True;
}
length += prefix.getLength() + type.getLength() + postfix.getLength();
sal_Bool withSeperator = sal_False;
if (destination.getStr()[destination.getLength()] != '\\' &&
destination.getStr()[destination.getLength()] != '/' &&
type.getStr()[0] != '\\' &&
type.getStr()[0] != '/')
{
length++;
withSeperator = sal_True;
}
OStringBuffer nameBuffer(length);
if (withPoint)
nameBuffer.append('.');
else
nameBuffer.append(destination.getStr(), destination.getLength());
if (withSeperator)
nameBuffer.append("/", 1);
OString tmpStr(type);
if (prefix.getLength() > 0)
{
tmpStr = type.replaceAt(type.lastIndexOf('/')+1, 0, prefix);
}
nameBuffer.append(tmpStr.getStr(), tmpStr.getLength());
nameBuffer.append(postfix.getStr(), postfix.getLength());
OString fileName(nameBuffer);
sal_Char token;
#ifdef SAL_UNX
fileName = fileName.replace('\\', '/');
token = '/';
#else
fileName = fileName.replace('/', '\\');
token = '\\';
#endif
nameBuffer = OStringBuffer(length);
sal_Int32 nIndex = 0;
do
{
nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());
if (nameBuffer.getLength() == 0 || OString(".") == nameBuffer.getStr())
{
nameBuffer.append(token);
continue;
}
#ifdef SAL_UNX
if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)
#else
if (mkdir((char*)nameBuffer.getStr()) == -1)
#endif
{
if ( errno == ENOENT )
return OString();
}
nameBuffer.append(token);
}
while ( nIndex >= 0 );
return fileName;
}
sal_Bool fileExists(const OString& fileName)
{
FILE *f= fopen(fileName.getStr(), "r");
if (f != NULL)
{
fclose(f);
return sal_True;
}
return sal_False;
}
sal_Bool checkFileContent(const OString& targetFileName, const OString& tmpFileName)
{
FILE *target = fopen(targetFileName.getStr(), "r");
FILE *tmp = fopen(tmpFileName.getStr(), "r");
sal_Bool ret = sal_False;
if (target != NULL && tmp != NULL)
{
sal_Bool bFindChanges = sal_False;
sal_Char buffer1[1024+1];
sal_Char buffer2[1024+1];
sal_Int32 n1 = 0;
sal_Int32 n2 = 0;
while ( !bFindChanges && !feof(target) && !feof(tmp))
{
n1 = fread(buffer1, sizeof(sal_Char), 1024, target);
n2 = fread(buffer2, sizeof(sal_Char), 1024, tmp);
if ( n1 != n2 )
{
bFindChanges = sal_True;
}
else
{
if ( rtl_compareMemory(buffer1, buffer2, n2) != 0 )
bFindChanges = sal_True;
}
}
fclose(target);
fclose(tmp);
if ( bFindChanges )
{
if ( !unlink(targetFileName.getStr()) )
if ( !rename(tmpFileName.getStr(), targetFileName.getStr()) )
ret = sal_True;
}
else
{
if ( !unlink(tmpFileName.getStr()) )
ret = sal_True;
}
}
return ret;
}
const OString inGlobalSet(const OUString & rValue)
{
OString sValue( OUStringToOString(rValue, RTL_TEXTENCODING_UTF8) );
static StringSet aGlobalMap;
StringSet::iterator iter = aGlobalMap.find( sValue );
if( iter != aGlobalMap.end() )
return *iter;
return *(aGlobalMap.insert( sValue ).first);
}
static sal_Bool isFileUrl(const OString& fileName)
{
if (fileName.indexOf("file://") == 0 )
return sal_True;
return sal_False;
}
OUString convertToFileUrl(const OString& fileName)
{
if ( isFileUrl(fileName) )
{
return OStringToOUString(fileName, osl_getThreadTextEncoding());
}
OUString uUrlFileName;
OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
if ( fileName.indexOf('.') == 0 || fileName.indexOf(SEPARATOR) < 0 )
{
OUString uWorkingDir;
if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None) {
OSL_ASSERT(false);
}
if (FileBase::getAbsoluteFileURL(uWorkingDir, uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
} else
{
if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
}
return uUrlFileName;
}
//*************************************************************************
// FileStream
//*************************************************************************
FileStream::FileStream()
{
}
FileStream::FileStream(const OString& name, FileAccessMode mode)
: m_pFile(NULL)
{
if ( name.getLength() > 0 )
{
m_name = name;
m_pFile = fopen(m_name, checkAccessMode(mode));
}
}
FileStream::~FileStream()
{
if ( isValid() )
{
fflush(m_pFile);
fclose(m_pFile);
}
}
sal_Bool FileStream::isValid()
{
if ( m_pFile )
return sal_True;
return sal_False;
}
void FileStream::open(const OString& name, FileAccessMode mode)
{
if ( name.getLength() > 0 )
{
m_name = name;
m_pFile = fopen(m_name, checkAccessMode(mode));
}
}
void FileStream::close()
{
if ( isValid() )
{
fflush(m_pFile);
fclose(m_pFile);
m_pFile = NULL;
m_name = OString();
}
}
sal_Int32 FileStream::getSize()
{
sal_Int32 pos = 0;
sal_Int32 size = 0;
if ( isValid() )
{
fflush(m_pFile);
pos = ftell(m_pFile);
if (!fseek(m_pFile, 0, SEEK_END))
size = ftell(m_pFile);
fseek(m_pFile, pos, SEEK_SET);
}
return size;
}
const sal_Char* FileStream::checkAccessMode(FileAccessMode mode)
{
switch( mode )
{
case FAM_READ:
return "r";
case FAM_WRITE:
return "w";
case FAM_APPEND:
return "a";
case FAM_READWRITE_EXIST:
return "r+";
case FAM_READWRITE:
return "w+";
case FAM_READAPPEND:
return "a+";
}
return "w+";
}
<commit_msg>INTEGRATION: CWS os2port01 (1.12.10); FILE MERGED 2006/12/28 15:02:27 ydario 1.12.10.1: OS/2 initial import.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: global.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: vg $ $Date: 2007-09-20 15:03:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
#ifndef _RTL_OSTRINGBUFFER_HXX_
#include <rtl/strbuf.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#include <stdlib.h>
#include <stdio.h>
#if defined(SAL_W32) || defined(SAL_OS2)
#include <io.h>
#include <direct.h>
#include <errno.h>
#endif
#ifdef UNX
#include <sys/stat.h>
#include <errno.h>
#include <unistd.h>
#endif
#ifndef _CODEMAKER_GLOBAL_HXX_
#include <codemaker/global.hxx>
#endif
#ifdef SAL_UNX
#define SEPARATOR '/'
#else
#define SEPARATOR '\\'
#endif
using namespace ::rtl;
using namespace ::osl;
OString createFileNameFromType( const OString& destination,
const OString typeName,
const OString postfix,
sal_Bool bLowerCase,
const OString prefix )
{
OString type(typeName);
if (bLowerCase)
{
type = typeName.toAsciiLowerCase();
}
sal_uInt32 length = destination.getLength();
sal_Bool withPoint = sal_False;
if (length == 0)
{
length++;
withPoint = sal_True;
}
length += prefix.getLength() + type.getLength() + postfix.getLength();
sal_Bool withSeperator = sal_False;
if (destination.getStr()[destination.getLength()] != '\\' &&
destination.getStr()[destination.getLength()] != '/' &&
type.getStr()[0] != '\\' &&
type.getStr()[0] != '/')
{
length++;
withSeperator = sal_True;
}
OStringBuffer nameBuffer(length);
if (withPoint)
nameBuffer.append('.');
else
nameBuffer.append(destination.getStr(), destination.getLength());
if (withSeperator)
nameBuffer.append("/", 1);
OString tmpStr(type);
if (prefix.getLength() > 0)
{
tmpStr = type.replaceAt(type.lastIndexOf('/')+1, 0, prefix);
}
nameBuffer.append(tmpStr.getStr(), tmpStr.getLength());
nameBuffer.append(postfix.getStr(), postfix.getLength());
OString fileName(nameBuffer);
sal_Char token;
#ifdef SAL_UNX
fileName = fileName.replace('\\', '/');
token = '/';
#else
fileName = fileName.replace('/', '\\');
token = '\\';
#endif
nameBuffer = OStringBuffer(length);
sal_Int32 nIndex = 0;
do
{
nameBuffer.append(fileName.getToken( 0, token, nIndex ).getStr());
if (nameBuffer.getLength() == 0 || OString(".") == nameBuffer.getStr())
{
nameBuffer.append(token);
continue;
}
#if defined(SAL_UNX) || defined(SAL_OS2)
if (mkdir((char*)nameBuffer.getStr(), 0777) == -1)
#else
if (mkdir((char*)nameBuffer.getStr()) == -1)
#endif
{
if ( errno == ENOENT )
return OString();
}
nameBuffer.append(token);
}
while ( nIndex >= 0 );
return fileName;
}
sal_Bool fileExists(const OString& fileName)
{
FILE *f= fopen(fileName.getStr(), "r");
if (f != NULL)
{
fclose(f);
return sal_True;
}
return sal_False;
}
sal_Bool checkFileContent(const OString& targetFileName, const OString& tmpFileName)
{
FILE *target = fopen(targetFileName.getStr(), "r");
FILE *tmp = fopen(tmpFileName.getStr(), "r");
sal_Bool ret = sal_False;
if (target != NULL && tmp != NULL)
{
sal_Bool bFindChanges = sal_False;
sal_Char buffer1[1024+1];
sal_Char buffer2[1024+1];
sal_Int32 n1 = 0;
sal_Int32 n2 = 0;
while ( !bFindChanges && !feof(target) && !feof(tmp))
{
n1 = fread(buffer1, sizeof(sal_Char), 1024, target);
n2 = fread(buffer2, sizeof(sal_Char), 1024, tmp);
if ( n1 != n2 )
{
bFindChanges = sal_True;
}
else
{
if ( rtl_compareMemory(buffer1, buffer2, n2) != 0 )
bFindChanges = sal_True;
}
}
fclose(target);
fclose(tmp);
if ( bFindChanges )
{
if ( !unlink(targetFileName.getStr()) )
if ( !rename(tmpFileName.getStr(), targetFileName.getStr()) )
ret = sal_True;
}
else
{
if ( !unlink(tmpFileName.getStr()) )
ret = sal_True;
}
}
return ret;
}
const OString inGlobalSet(const OUString & rValue)
{
OString sValue( OUStringToOString(rValue, RTL_TEXTENCODING_UTF8) );
static StringSet aGlobalMap;
StringSet::iterator iter = aGlobalMap.find( sValue );
if( iter != aGlobalMap.end() )
return *iter;
return *(aGlobalMap.insert( sValue ).first);
}
static sal_Bool isFileUrl(const OString& fileName)
{
if (fileName.indexOf("file://") == 0 )
return sal_True;
return sal_False;
}
OUString convertToFileUrl(const OString& fileName)
{
if ( isFileUrl(fileName) )
{
return OStringToOUString(fileName, osl_getThreadTextEncoding());
}
OUString uUrlFileName;
OUString uFileName(fileName.getStr(), fileName.getLength(), osl_getThreadTextEncoding());
if ( fileName.indexOf('.') == 0 || fileName.indexOf(SEPARATOR) < 0 )
{
OUString uWorkingDir;
if (osl_getProcessWorkingDir(&uWorkingDir.pData) != osl_Process_E_None) {
OSL_ASSERT(false);
}
if (FileBase::getAbsoluteFileURL(uWorkingDir, uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
} else
{
if (FileBase::getFileURLFromSystemPath(uFileName, uUrlFileName)
!= FileBase::E_None)
{
OSL_ASSERT(false);
}
}
return uUrlFileName;
}
//*************************************************************************
// FileStream
//*************************************************************************
FileStream::FileStream()
{
}
FileStream::FileStream(const OString& name, FileAccessMode mode)
: m_pFile(NULL)
{
if ( name.getLength() > 0 )
{
m_name = name;
m_pFile = fopen(m_name, checkAccessMode(mode));
}
}
FileStream::~FileStream()
{
if ( isValid() )
{
fflush(m_pFile);
fclose(m_pFile);
}
}
sal_Bool FileStream::isValid()
{
if ( m_pFile )
return sal_True;
return sal_False;
}
void FileStream::open(const OString& name, FileAccessMode mode)
{
if ( name.getLength() > 0 )
{
m_name = name;
m_pFile = fopen(m_name, checkAccessMode(mode));
}
}
void FileStream::close()
{
if ( isValid() )
{
fflush(m_pFile);
fclose(m_pFile);
m_pFile = NULL;
m_name = OString();
}
}
sal_Int32 FileStream::getSize()
{
sal_Int32 pos = 0;
sal_Int32 size = 0;
if ( isValid() )
{
fflush(m_pFile);
pos = ftell(m_pFile);
if (!fseek(m_pFile, 0, SEEK_END))
size = ftell(m_pFile);
fseek(m_pFile, pos, SEEK_SET);
}
return size;
}
const sal_Char* FileStream::checkAccessMode(FileAccessMode mode)
{
switch( mode )
{
case FAM_READ:
return "r";
case FAM_WRITE:
return "w";
case FAM_APPEND:
return "a";
case FAM_READWRITE_EXIST:
return "r+";
case FAM_READWRITE:
return "w+";
case FAM_READAPPEND:
return "a+";
}
return "w+";
}
<|endoftext|>
|
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018-2019 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/webbrowser/processors/webbrowserprocessor.h>
#include <modules/webbrowser/interaction/cefinteractionhandler.h>
#include <modules/webbrowser/webbrowsermodule.h>
#include <modules/opengl/image/layergl.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/properties/minmaxproperty.h>
#include <inviwo/core/properties/propertyfactory.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/utilities.h>
#include <warn/push>
#include <warn/ignore/all>
#include <include/cef_app.h>
#include <warn/pop>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo WebBrowserProcessor::processorInfo_{
"org.inviwo.webbrowser", // Class identifier
"Web browser", // Display name
"Web", // Category
CodeState::Stable, // Code state
"GL, Web Browser", // Tags
};
const ProcessorInfo WebBrowserProcessor::getProcessorInfo() const { return processorInfo_; }
WebBrowserProcessor::WebBrowserProcessor()
: Processor()
// Output from CEF is 8-bits per channel
, background_("background")
, outport_("webpage", DataVec4UInt8::get())
, fileName_("fileName", "HTML file", "")
, autoReloadFile_("autoReloadFile", "Auto Reload", true)
, url_("URL", "URL", "http://www.inviwo.org")
, reload_("reload", "Reload")
, addPropertyGroup_("addProperty", "Add property to synchronize")
, type_("property", "Property")
, propertyHtmlId_("propertyHtmlId", "Html id")
, add_("add", "Add")
, runJS_("runJS", "Run JS")
, js_("js", "JavaScript", "", InvalidationLevel::Valid)
, sourceType_("sourceType", "Source",
{{"localFile", "Local File", SourceType::LocalFile},
{"webAddress", "Web Address", SourceType::WebAddress}})
, picking_(this, 1, [&](PickingEvent* p) { cefInteractionHandler_.handlePickingEvent(p); })
, cefToInviwoImageConverter_(picking_.getColor())
, renderHandler_(new RenderHandlerGL([&]() {
// Called as soon as new content is available
// Queue an invalidation
// Note: no need to queue invalidation using dispathFront since
// RenderHandler calls will be made from the same thread.
// dispatchFront([&] {
invalidate(InvalidationLevel::InvalidOutput);
//});
}))
, browserClient_(new WebBrowserClient(renderHandler_)) {
addPort(background_);
background_.setOptional(true);
addPort(outport_);
addProperty(sourceType_);
addProperty(fileName_);
addProperty(autoReloadFile_);
addProperty(url_);
url_.setVisible(false);
addProperty(reload_);
addProperty(runJS_);
addProperty(js_);
auto updateVisibility = [this]() {
fileName_.setVisible(sourceType_ == SourceType::LocalFile);
autoReloadFile_.setVisible(sourceType_ == SourceType::LocalFile);
url_.setVisible(sourceType_ == SourceType::WebAddress);
};
updateVisibility();
auto reload = [this]() { browser_->GetMainFrame()->LoadURL(getSource()); };
sourceType_.onChange([this, reload, updateVisibility]() {
updateVisibility();
reload();
});
fileName_.onChange([this, reload]() {
if (autoReloadFile_) {
fileObserver_.setFilename(fileName_);
}
reload();
});
autoReloadFile_.onChange([this]() {
if (autoReloadFile_) {
fileObserver_.setFilename(fileName_);
} else {
fileObserver_.stop();
}
});
url_.onChange(reload);
reload_.onChange(reload);
fileObserver_.onChange([this, reload]() {
if (sourceType_ == SourceType::LocalFile) {
reload();
}
});
// Do not serialize options, they are generated in code
type_.setSerializationMode(PropertySerializationMode::None);
addPropertyGroup_.addProperty(type_);
addPropertyGroup_.addProperty(propertyHtmlId_);
addPropertyGroup_.addProperty(add_);
addProperty(addPropertyGroup_);
// Setup CEF browser
CefWindowInfo window_info;
CefBrowserSettings browserSettings;
// Enable loading files from other locations than where the .html file is
browserSettings.file_access_from_file_urls = STATE_ENABLED;
browserSettings.windowless_frame_rate = 30; // Must be between 1-60, 30 is default
// in linux set a gtk widget, in windows a hwnd. If not available set nullptr - may cause
// some render errors, in context-menu and plugins.
window_info.SetAsWindowless(nullptr); // nullptr means no transparency (site background colour)
// Note that browserClient_ outlives this class so make sure to remove renderHandler_ in
// destructor
browser_ = CefBrowserHost::CreateBrowserSync(window_info, browserClient_, getSource(),
browserSettings, nullptr);
// Observe when page has loaded
browserClient_->addLoadHandler(this);
// Do not process until frame is loaded
isReady_.setUpdate([this]() { return allInportsAreReady() && !isBrowserLoading_; });
// Inject events into CEF browser_
cefInteractionHandler_.setHost(browser_->GetHost());
cefInteractionHandler_.setRenderHandler(renderHandler_);
addInteractionHandler(&cefInteractionHandler_);
// Add all supported properties
auto app = InviwoApplication::getPtr();
for (auto propKey : app->getPropertyFactory()->getKeys()) {
auto prop = app->getPropertyFactory()->create(propKey);
if (browserClient_->propertyCefSynchronizer_->htmlWidgetFactory_.hasKey(prop.get())) {
type_.addOption(prop->getClassIdentifier(),
filesystem::getFileExtension(prop->getClassIdentifier()), type_.size());
}
}
type_.setCurrentStateAsDefault();
propertyHtmlId_ = type_.getSelectedDisplayName();
type_.onChange([&]() { propertyHtmlId_ = type_.getSelectedDisplayName(); });
add_.onChange([&]() {
auto key = type_.getSelectedIdentifier();
auto p = getInviwoApplication()->getPropertyFactory()->create(key);
auto id = propertyHtmlId_.get();
try {
util::validateIdentifier(id, "Property", IvwContext);
} catch (Exception& ex) {
LogError(ex.getMessage());
return;
}
if (getPropertyByIdentifier(id) != nullptr) {
LogError("Property with same id already added");
return;
}
p->setIdentifier(id);
p->setDisplayName(id);
p->setSerializationMode(PropertySerializationMode::All);
// InvalidationLevel::Valid is used to not get
// invalidations from both CEF (html) and Qt
p->setInvalidationLevel(InvalidationLevel::Valid);
// Add property to processor before propertyCefSynchronizer to
// include processor in property path
addProperty(p.get(), true);
browserClient_->propertyCefSynchronizer_->startSynchronize(p.get(), id);
// Must reload page to connect property with Frame, see PropertyCefSynchronizer::OnLoadEnd
browser_->GetMainFrame()->LoadURL(getSource());
p.release();
});
}
std::string WebBrowserProcessor::getSource() {
std::string sourceString;
if (sourceType_.get() == SourceType::LocalFile) {
sourceString = "file://" + fileName_.get();
} else if (sourceType_.get() == SourceType::WebAddress) {
sourceString = url_.get();
}
#ifndef NDEBUG
// CEF does not allow empty urls in debug mode
if (sourceString.empty()) {
sourceString = "https://www.inviwo.org";
}
#endif
return sourceString;
}
WebBrowserProcessor::~WebBrowserProcessor() {
browserClient_->removeLoadHandler(this);
// Force close browser
browser_->GetHost()->CloseBrowser(true);
// Remove render handler since browserClient_ might not be destroyed until CefShutdown() is
// called
browserClient_->SetRenderHandler(NULL);
}
void WebBrowserProcessor::deserialize(Deserializer& d) {
Processor::deserialize(d);
for (auto prop : *this) {
if (prop == &sourceType_ || prop == &fileName_ || prop == &url_ || prop == &reload_ ||
prop == &addPropertyGroup_ || prop == &type_ || prop == &propertyHtmlId_ ||
prop == &add_) {
continue;
}
browserClient_->propertyCefSynchronizer_->startSynchronize(prop, prop->getIdentifier());
}
// Must reload page to connect property with Frame, see PropertyCefSynchronizer::OnLoadEnd
browser_->GetMainFrame()->LoadURL(getSource());
}
void WebBrowserProcessor::OnLoadingStateChange(CefRefPtr<CefBrowser> browser, bool isLoading,
bool /*canGoBack*/, bool /*canGoForward*/) {
if (browser_ && browser->GetIdentifier() == browser_->GetIdentifier()) {
isBrowserLoading_ = isLoading;
isReady_.update();
}
}
void WebBrowserProcessor::process() {
if (js_.isModified()) {
browser_->GetMainFrame()->ExecuteJavaScript(js_.get(), "", 1);
}
// Vertical flip of CEF output image
cefToInviwoImageConverter_.convert(renderHandler_->getTexture2D(), outport_, &background_);
}
} // namespace inviwo
<commit_msg>Webbrowser: Prevent empty script execution (error on Mac)<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018-2019 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/webbrowser/processors/webbrowserprocessor.h>
#include <modules/webbrowser/interaction/cefinteractionhandler.h>
#include <modules/webbrowser/webbrowsermodule.h>
#include <modules/opengl/image/layergl.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/properties/minmaxproperty.h>
#include <inviwo/core/properties/propertyfactory.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/utilities.h>
#include <warn/push>
#include <warn/ignore/all>
#include <include/cef_app.h>
#include <warn/pop>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo WebBrowserProcessor::processorInfo_{
"org.inviwo.webbrowser", // Class identifier
"Web browser", // Display name
"Web", // Category
CodeState::Stable, // Code state
"GL, Web Browser", // Tags
};
const ProcessorInfo WebBrowserProcessor::getProcessorInfo() const { return processorInfo_; }
WebBrowserProcessor::WebBrowserProcessor()
: Processor()
// Output from CEF is 8-bits per channel
, background_("background")
, outport_("webpage", DataVec4UInt8::get())
, fileName_("fileName", "HTML file", "")
, autoReloadFile_("autoReloadFile", "Auto Reload", true)
, url_("URL", "URL", "http://www.inviwo.org")
, reload_("reload", "Reload")
, addPropertyGroup_("addProperty", "Add property to synchronize")
, type_("property", "Property")
, propertyHtmlId_("propertyHtmlId", "Html id")
, add_("add", "Add")
, runJS_("runJS", "Run JS")
, js_("js", "JavaScript", "", InvalidationLevel::Valid)
, sourceType_("sourceType", "Source",
{{"localFile", "Local File", SourceType::LocalFile},
{"webAddress", "Web Address", SourceType::WebAddress}})
, picking_(this, 1, [&](PickingEvent* p) { cefInteractionHandler_.handlePickingEvent(p); })
, cefToInviwoImageConverter_(picking_.getColor())
, renderHandler_(new RenderHandlerGL([&]() {
// Called as soon as new content is available
// Queue an invalidation
// Note: no need to queue invalidation using dispathFront since
// RenderHandler calls will be made from the same thread.
// dispatchFront([&] {
invalidate(InvalidationLevel::InvalidOutput);
//});
}))
, browserClient_(new WebBrowserClient(renderHandler_)) {
addPort(background_);
background_.setOptional(true);
addPort(outport_);
addProperty(sourceType_);
addProperty(fileName_);
addProperty(autoReloadFile_);
addProperty(url_);
url_.setVisible(false);
addProperty(reload_);
addProperty(runJS_);
addProperty(js_);
auto updateVisibility = [this]() {
fileName_.setVisible(sourceType_ == SourceType::LocalFile);
autoReloadFile_.setVisible(sourceType_ == SourceType::LocalFile);
url_.setVisible(sourceType_ == SourceType::WebAddress);
};
updateVisibility();
auto reload = [this]() { browser_->GetMainFrame()->LoadURL(getSource()); };
sourceType_.onChange([this, reload, updateVisibility]() {
updateVisibility();
reload();
});
fileName_.onChange([this, reload]() {
if (autoReloadFile_) {
fileObserver_.setFilename(fileName_);
}
reload();
});
autoReloadFile_.onChange([this]() {
if (autoReloadFile_) {
fileObserver_.setFilename(fileName_);
} else {
fileObserver_.stop();
}
});
url_.onChange(reload);
reload_.onChange(reload);
fileObserver_.onChange([this, reload]() {
if (sourceType_ == SourceType::LocalFile) {
reload();
}
});
// Do not serialize options, they are generated in code
type_.setSerializationMode(PropertySerializationMode::None);
addPropertyGroup_.addProperty(type_);
addPropertyGroup_.addProperty(propertyHtmlId_);
addPropertyGroup_.addProperty(add_);
addProperty(addPropertyGroup_);
// Setup CEF browser
CefWindowInfo window_info;
CefBrowserSettings browserSettings;
// Enable loading files from other locations than where the .html file is
browserSettings.file_access_from_file_urls = STATE_ENABLED;
browserSettings.windowless_frame_rate = 30; // Must be between 1-60, 30 is default
// in linux set a gtk widget, in windows a hwnd. If not available set nullptr - may cause
// some render errors, in context-menu and plugins.
window_info.SetAsWindowless(nullptr); // nullptr means no transparency (site background colour)
// Note that browserClient_ outlives this class so make sure to remove renderHandler_ in
// destructor
browser_ = CefBrowserHost::CreateBrowserSync(window_info, browserClient_, getSource(),
browserSettings, nullptr);
// Observe when page has loaded
browserClient_->addLoadHandler(this);
// Do not process until frame is loaded
isReady_.setUpdate([this]() { return allInportsAreReady() && !isBrowserLoading_; });
// Inject events into CEF browser_
cefInteractionHandler_.setHost(browser_->GetHost());
cefInteractionHandler_.setRenderHandler(renderHandler_);
addInteractionHandler(&cefInteractionHandler_);
// Add all supported properties
auto app = InviwoApplication::getPtr();
for (auto propKey : app->getPropertyFactory()->getKeys()) {
auto prop = app->getPropertyFactory()->create(propKey);
if (browserClient_->propertyCefSynchronizer_->htmlWidgetFactory_.hasKey(prop.get())) {
type_.addOption(prop->getClassIdentifier(),
filesystem::getFileExtension(prop->getClassIdentifier()), type_.size());
}
}
type_.setCurrentStateAsDefault();
propertyHtmlId_ = type_.getSelectedDisplayName();
type_.onChange([&]() { propertyHtmlId_ = type_.getSelectedDisplayName(); });
add_.onChange([&]() {
auto key = type_.getSelectedIdentifier();
auto p = getInviwoApplication()->getPropertyFactory()->create(key);
auto id = propertyHtmlId_.get();
try {
util::validateIdentifier(id, "Property", IvwContext);
} catch (Exception& ex) {
LogError(ex.getMessage());
return;
}
if (getPropertyByIdentifier(id) != nullptr) {
LogError("Property with same id already added");
return;
}
p->setIdentifier(id);
p->setDisplayName(id);
p->setSerializationMode(PropertySerializationMode::All);
// InvalidationLevel::Valid is used to not get
// invalidations from both CEF (html) and Qt
p->setInvalidationLevel(InvalidationLevel::Valid);
// Add property to processor before propertyCefSynchronizer to
// include processor in property path
addProperty(p.get(), true);
browserClient_->propertyCefSynchronizer_->startSynchronize(p.get(), id);
// Must reload page to connect property with Frame, see PropertyCefSynchronizer::OnLoadEnd
browser_->GetMainFrame()->LoadURL(getSource());
p.release();
});
}
std::string WebBrowserProcessor::getSource() {
std::string sourceString;
if (sourceType_.get() == SourceType::LocalFile) {
sourceString = "file://" + fileName_.get();
} else if (sourceType_.get() == SourceType::WebAddress) {
sourceString = url_.get();
}
#ifndef NDEBUG
// CEF does not allow empty urls in debug mode
if (sourceString.empty()) {
sourceString = "https://www.inviwo.org";
}
#endif
return sourceString;
}
WebBrowserProcessor::~WebBrowserProcessor() {
browserClient_->removeLoadHandler(this);
// Force close browser
browser_->GetHost()->CloseBrowser(true);
// Remove render handler since browserClient_ might not be destroyed until CefShutdown() is
// called
browserClient_->SetRenderHandler(NULL);
}
void WebBrowserProcessor::deserialize(Deserializer& d) {
Processor::deserialize(d);
for (auto prop : *this) {
if (prop == &sourceType_ || prop == &fileName_ || prop == &url_ || prop == &reload_ ||
prop == &addPropertyGroup_ || prop == &type_ || prop == &propertyHtmlId_ ||
prop == &add_) {
continue;
}
browserClient_->propertyCefSynchronizer_->startSynchronize(prop, prop->getIdentifier());
}
// Must reload page to connect property with Frame, see PropertyCefSynchronizer::OnLoadEnd
browser_->GetMainFrame()->LoadURL(getSource());
}
void WebBrowserProcessor::OnLoadingStateChange(CefRefPtr<CefBrowser> browser, bool isLoading,
bool /*canGoBack*/, bool /*canGoForward*/) {
if (browser_ && browser->GetIdentifier() == browser_->GetIdentifier()) {
isBrowserLoading_ = isLoading;
isReady_.update();
}
}
void WebBrowserProcessor::process() {
if (js_.isModified() && !js_.get().empty()) {
browser_->GetMainFrame()->ExecuteJavaScript(js_.get(), "", 1);
}
// Vertical flip of CEF output image
cefToInviwoImageConverter_.convert(renderHandler_->getTexture2D(), outport_, &background_);
}
} // namespace inviwo
<|endoftext|>
|
<commit_before>/**
* The MIT License (MIT)
*
* Copyright © 2019 Ruben Van Boxem
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**/
#include "ostream.h++"
#include <iostream>
namespace skui::css
{
template<typename... ValueTypes>
std::ostream& operator<<(std::ostream& os, const std::variant<ValueTypes...>& value)
{
std::visit([&os](auto&& v) { os << v; }, value);
return os;
}
std::ostream& operator<<(std::ostream& os, const inherit_t&)
{
return os << "inherit";
}
std::ostream& operator<<(std::ostream& os, const initial_t&)
{
return os << "initial";
}
std::ostream& operator<<(std::ostream& os, const color& color)
{
core::ostream_format_keeper keeper(os);
return os << std::hex << std::uint32_t(color);
}
std::ostream& operator<<(std::ostream& os, const unit unit)
{
switch(unit)
{
case unit::mm:
return os << "mm";
case unit::cm:
return os << "cm";
case unit::in:
return os << "in";
case unit::px:
return os << "px";
case unit::pt:
return os << "pt";
case unit::pc:
return os << "pc";
case unit::em:
return os << "em";
case unit::ex:
return os << "ex";
case unit::ch:
return os << "ch";
case unit::rem:
return os << "rem";
case unit::vw:
return os << "vw";
case unit::vh:
return os << "vh";
case unit::vmin:
return os << "vmin";
case unit::vmax:
return os << "vmax";
case unit::percentage:
return os << "%";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const length& length)
{
return os << length.value << ' ' << length.unit;
}
std::ostream& operator<<(std::ostream& os, const length_with_offset& length_with_offset)
{
os << length_with_offset.value;
if(length_with_offset.offset != length{})
{
os << " (offset: " << length_with_offset.offset << ')';
}
return os;
}
std::ostream& operator<<(std::ostream& os, const position& position)
{
if(position == top)
os << "top";
else if(position == center)
os << "center";
else if(position == bottom)
os << "bottom";
else if(position == left)
os << "left";
else if(position == right)
os << "right";
else if(position == top_left)
os << "top left";
else if(position == top_right)
os << "top right";
else if(position == bottom_left)
os << "bottom left";
else if(position == bottom_right)
os << "bottom right";
else
os << "position(" << position.x << ", " << position.y << ")";
return os;
}
std::ostream& operator<<(std::ostream& os, const skui::css::time& time)
{
return os << time.count() << " ms";
}
std::ostream& operator<<(std::ostream& os, const steps& steps)
{
return os << "steps(" << steps.intervals << ", " << steps.change << ')';
}
std::ostream& operator<<(std::ostream& os, const cubic_bezier& cubic_bezier)
{
return os << "cubic-bezier(" << cubic_bezier.x1 << ", " << cubic_bezier.y1 << ", "
<< cubic_bezier.x2 << ", " << cubic_bezier.y2 << ')';
}
std::ostream& operator<<(std::ostream& os, const timing_function& timing_function)
{
std::visit([&os](const auto& value) { os << value; }, timing_function);
return os;
}
std::ostream& operator<<(std::ostream& os, const animation_direction& direction)
{
switch(direction)
{
case animation_direction::normal:
return os << "normal";
case animation_direction::reverse:
return os << "reverse";
case animation_direction::alternate:
return os << "alternate";
case animation_direction::alternate_reverse:
return os << "alternate-reverse";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const fill_mode& mode)
{
switch(mode)
{
case fill_mode::none:
return os << "none";
case fill_mode::forwards:
return os << "forwards";
case fill_mode::backwards:
return os << "backwards";
case fill_mode::both:
return os << "both";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const play_state& state)
{
switch(state)
{
case play_state::running:
return os << "running";
case play_state::paused:
return os << "paused";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const infinite_t&)
{
return os << "infinite";
}
std::ostream& operator<<(std::ostream& os, const animation& animation)
{
return os << "animation\n{\n"
" name: " << animation.name << ";\n"
" duration: " << /*animation.duration <<*/ ";\n"
" timing-function: " << animation.timing_function << ";\n"
" delay: " << /*animation.delay <<*/ ";\n"
" iteration_count: " << animation.iteration_count << ";\n"
" direction: " << animation.direction << ";\n"
" fill_mode: " << animation.fill_mode << ";\n"
" play_state: " << animation.play_state << ";\n"
"}";
}
std::ostream& operator<<(std::ostream& os,
const std::vector<skui::css::color_stop>& colors)
{
for(auto it = colors.begin(); it != colors.end(); ++it)
{
os << *it;
if(it+1 != colors.end())
os << ", ";
}
return os;
}
std::ostream&operator<<(std::ostream& os, const color_stop& color_stop)
{
os << "color-stop(" << color_stop.color;
if(color_stop.stop)
{
os << ", " << *color_stop.stop;
}
return os << ")";
}
std::ostream& operator<<(std::ostream& os,
const linear_gradient& linear_gradient)
{
if(linear_gradient.repeating)
os << "repeating-";
os << "linear-gradient(to ";
std::visit([&os](auto&& direction) { os << direction; }, linear_gradient.direction);
return os << ", " << linear_gradient.colors << ")";
}
}
<commit_msg>Improve css::color ostream operator to always output same format.<commit_after>/**
* The MIT License (MIT)
*
* Copyright © 2019 Ruben Van Boxem
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
**/
#include "ostream.h++"
#include <iostream>
namespace skui::css
{
template<typename... ValueTypes>
std::ostream& operator<<(std::ostream& os, const std::variant<ValueTypes...>& value)
{
std::visit([&os](auto&& v) { os << v; }, value);
return os;
}
std::ostream& operator<<(std::ostream& os, const inherit_t&)
{
return os << "inherit";
}
std::ostream& operator<<(std::ostream& os, const initial_t&)
{
return os << "initial";
}
std::ostream& operator<<(std::ostream& os, const color& color)
{
core::ostream_format_keeper keeper(os);
return os << std::setfill('0') << std::setw(8) << std::hex << std::uint32_t(color);
}
std::ostream& operator<<(std::ostream& os, const unit unit)
{
switch(unit)
{
case unit::mm:
return os << "mm";
case unit::cm:
return os << "cm";
case unit::in:
return os << "in";
case unit::px:
return os << "px";
case unit::pt:
return os << "pt";
case unit::pc:
return os << "pc";
case unit::em:
return os << "em";
case unit::ex:
return os << "ex";
case unit::ch:
return os << "ch";
case unit::rem:
return os << "rem";
case unit::vw:
return os << "vw";
case unit::vh:
return os << "vh";
case unit::vmin:
return os << "vmin";
case unit::vmax:
return os << "vmax";
case unit::percentage:
return os << "%";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const length& length)
{
return os << length.value << ' ' << length.unit;
}
std::ostream& operator<<(std::ostream& os, const length_with_offset& length_with_offset)
{
os << length_with_offset.value;
if(length_with_offset.offset != length{})
{
os << " (offset: " << length_with_offset.offset << ')';
}
return os;
}
std::ostream& operator<<(std::ostream& os, const position& position)
{
if(position == top)
os << "top";
else if(position == center)
os << "center";
else if(position == bottom)
os << "bottom";
else if(position == left)
os << "left";
else if(position == right)
os << "right";
else if(position == top_left)
os << "top left";
else if(position == top_right)
os << "top right";
else if(position == bottom_left)
os << "bottom left";
else if(position == bottom_right)
os << "bottom right";
else
os << "position(" << position.x << ", " << position.y << ")";
return os;
}
std::ostream& operator<<(std::ostream& os, const skui::css::time& time)
{
return os << time.count() << " ms";
}
std::ostream& operator<<(std::ostream& os, const steps& steps)
{
return os << "steps(" << steps.intervals << ", " << steps.change << ')';
}
std::ostream& operator<<(std::ostream& os, const cubic_bezier& cubic_bezier)
{
return os << "cubic-bezier(" << cubic_bezier.x1 << ", " << cubic_bezier.y1 << ", "
<< cubic_bezier.x2 << ", " << cubic_bezier.y2 << ')';
}
std::ostream& operator<<(std::ostream& os, const timing_function& timing_function)
{
std::visit([&os](const auto& value) { os << value; }, timing_function);
return os;
}
std::ostream& operator<<(std::ostream& os, const animation_direction& direction)
{
switch(direction)
{
case animation_direction::normal:
return os << "normal";
case animation_direction::reverse:
return os << "reverse";
case animation_direction::alternate:
return os << "alternate";
case animation_direction::alternate_reverse:
return os << "alternate-reverse";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const fill_mode& mode)
{
switch(mode)
{
case fill_mode::none:
return os << "none";
case fill_mode::forwards:
return os << "forwards";
case fill_mode::backwards:
return os << "backwards";
case fill_mode::both:
return os << "both";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const play_state& state)
{
switch(state)
{
case play_state::running:
return os << "running";
case play_state::paused:
return os << "paused";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const infinite_t&)
{
return os << "infinite";
}
std::ostream& operator<<(std::ostream& os, const animation& animation)
{
return os << "animation\n{\n"
" name: " << animation.name << ";\n"
" duration: " << /*animation.duration <<*/ ";\n"
" timing-function: " << animation.timing_function << ";\n"
" delay: " << /*animation.delay <<*/ ";\n"
" iteration_count: " << animation.iteration_count << ";\n"
" direction: " << animation.direction << ";\n"
" fill_mode: " << animation.fill_mode << ";\n"
" play_state: " << animation.play_state << ";\n"
"}";
}
std::ostream& operator<<(std::ostream& os,
const std::vector<skui::css::color_stop>& colors)
{
for(auto it = colors.begin(); it != colors.end(); ++it)
{
os << *it;
if(it+1 != colors.end())
os << ", ";
}
return os;
}
std::ostream&operator<<(std::ostream& os, const color_stop& color_stop)
{
os << "color-stop(" << color_stop.color;
if(color_stop.stop)
{
os << ", " << *color_stop.stop;
}
return os << ")";
}
std::ostream& operator<<(std::ostream& os,
const linear_gradient& linear_gradient)
{
if(linear_gradient.repeating)
os << "repeating-";
os << "linear-gradient(to ";
std::visit([&os](auto&& direction) { os << direction; }, linear_gradient.direction);
return os << ", " << linear_gradient.colors << ")";
}
}
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, 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 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.
*********************************************************************/
/* Author: Dan Greenwald */
#include <moveit/warehouse/state_storage.h>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <ros/ros.h>
#include <moveit_msgs/SaveRobotStateToWarehouse.h>
#include <moveit_msgs/ListRobotStatesInWarehouse.h>
#include <moveit_msgs/GetRobotStateFromWarehouse.h>
#include <moveit_msgs/CheckIfRobotStateExistsInWarehouse.h>
#include <moveit_msgs/DeleteRobotStateFromWarehouse.h>
#include <moveit_msgs/RenameRobotStateInWarehouse.h>
static const std::string ROBOT_DESCRIPTION="robot_description";
bool store_state(moveit_msgs::SaveRobotStateToWarehouse::Request& request,
moveit_msgs::SaveRobotStateToWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
const moveit_msgs::RobotState& state = request.state;
if ("" == request.name)
{
ROS_ERROR("You must specify a name to store a state");
return response.success = false;
}
rs->addRobotState(request.state, request.name, request.robot);
return response.success = true;
}
bool list_states(moveit_msgs::ListRobotStatesInWarehouse::Request& request,
moveit_msgs::ListRobotStatesInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
if ("" == request.regex)
{
rs->getKnownRobotStates(response.states, request.robot);
}
else
{
rs->getKnownRobotStates(request.regex, response.states, request.robot);
}
return true;
}
bool has_state(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request& request,
moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
response.exists = rs->hasRobotState(request.name, request.robot);
return true;
}
bool get_state(moveit_msgs::GetRobotStateFromWarehouse::Request& request,
moveit_msgs::GetRobotStateFromWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
moveit_warehouse::RobotStateWithMetadata state_buffer;
rs->getRobotState(state_buffer, request.name, request.robot);
response.state = static_cast<const moveit_msgs::RobotState&>(*state_buffer);
return true;
}
bool rename_state(moveit_msgs::RenameRobotStateInWarehouse::Request& request,
moveit_msgs::RenameRobotStateInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
rs->renameRobotState(request.old_name, request.new_name, request.robot);
return true;
}
bool delete_state(moveit_msgs::DeleteRobotStateFromWarehouse::Request& request,
moveit_msgs::DeleteRobotStateFromWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
rs->removeRobotState(request.name, request.robot);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "moveit_warehouse_services");
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle node("~");
std::string host; int port;
node.param<std::string>("/warehouse_host", host, "");
node.param<int>("/warehouse_port", port, 0);
ROS_INFO("Connecting to warehouse on %s:%d", host.c_str(), port);
moveit_warehouse::RobotStateStorage rs(host, port);
std::vector<std::string> names;
rs.getKnownRobotStates(names);
if (names.empty())
ROS_INFO("There are no previously stored robot states");
else
{
ROS_INFO("Previously stored robot states:");
for (std::size_t i = 0 ; i < names.size() ; ++i)
ROS_INFO(" * %s", names[i].c_str());
}
boost::function<bool(moveit_msgs::SaveRobotStateToWarehouse::Request& request,
moveit_msgs::SaveRobotStateToWarehouse::Response& response)>
save_cb = boost::bind(&store_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::ListRobotStatesInWarehouse::Request& request,
moveit_msgs::ListRobotStatesInWarehouse::Response& response)>
list_cb = boost::bind(&list_states, _1, _2, &rs);
boost::function<bool(moveit_msgs::GetRobotStateFromWarehouse::Request& request,
moveit_msgs::GetRobotStateFromWarehouse::Response& response)>
get_cb = boost::bind(&get_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request& request,
moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response)>
has_cb = boost::bind(&has_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::RenameRobotStateInWarehouse::Request& request,
moveit_msgs::RenameRobotStateInWarehouse::Response& response)>
rename_cb = boost::bind(&rename_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::DeleteRobotStateFromWarehouse::Request& request,
moveit_msgs::DeleteRobotStateFromWarehouse::Response& response)>
delete_cb = boost::bind(&delete_state, _1, _2, &rs);
ros::ServiceServer save_state_server = node.advertiseService("save_robot_state", save_cb);
ros::ServiceServer list_states_server = node.advertiseService("list_robot_states", list_cb);
ros::ServiceServer get_state_server = node.advertiseService("get_robot_state", get_cb);
ros::ServiceServer has_state_server = node.advertiseService("has_robot_state", has_cb);
ros::ServiceServer rename_state_server = node.advertiseService("rename_robot_state", rename_cb);
ros::ServiceServer delete_state_server = node.advertiseService("delete_robot_state", delete_cb);
ros::waitForShutdown();
return 0;
}
<commit_msg>removed extraneous includes<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, 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 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.
*********************************************************************/
/* Author: Dan Greenwald */
#include <ros/ros.h>
#include <moveit/warehouse/state_storage.h>
#include <moveit_msgs/SaveRobotStateToWarehouse.h>
#include <moveit_msgs/ListRobotStatesInWarehouse.h>
#include <moveit_msgs/GetRobotStateFromWarehouse.h>
#include <moveit_msgs/CheckIfRobotStateExistsInWarehouse.h>
#include <moveit_msgs/DeleteRobotStateFromWarehouse.h>
#include <moveit_msgs/RenameRobotStateInWarehouse.h>
static const std::string ROBOT_DESCRIPTION="robot_description";
bool store_state(moveit_msgs::SaveRobotStateToWarehouse::Request& request,
moveit_msgs::SaveRobotStateToWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
const moveit_msgs::RobotState& state = request.state;
if ("" == request.name)
{
ROS_ERROR("You must specify a name to store a state");
return response.success = false;
}
rs->addRobotState(request.state, request.name, request.robot);
return response.success = true;
}
bool list_states(moveit_msgs::ListRobotStatesInWarehouse::Request& request,
moveit_msgs::ListRobotStatesInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
if ("" == request.regex)
{
rs->getKnownRobotStates(response.states, request.robot);
}
else
{
rs->getKnownRobotStates(request.regex, response.states, request.robot);
}
return true;
}
bool has_state(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request& request,
moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
response.exists = rs->hasRobotState(request.name, request.robot);
return true;
}
bool get_state(moveit_msgs::GetRobotStateFromWarehouse::Request& request,
moveit_msgs::GetRobotStateFromWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
moveit_warehouse::RobotStateWithMetadata state_buffer;
rs->getRobotState(state_buffer, request.name, request.robot);
response.state = static_cast<const moveit_msgs::RobotState&>(*state_buffer);
return true;
}
bool rename_state(moveit_msgs::RenameRobotStateInWarehouse::Request& request,
moveit_msgs::RenameRobotStateInWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
rs->renameRobotState(request.old_name, request.new_name, request.robot);
return true;
}
bool delete_state(moveit_msgs::DeleteRobotStateFromWarehouse::Request& request,
moveit_msgs::DeleteRobotStateFromWarehouse::Response& response,
moveit_warehouse::RobotStateStorage* rs)
{
rs->removeRobotState(request.name, request.robot);
return true;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "moveit_warehouse_services");
ros::AsyncSpinner spinner(1);
spinner.start();
ros::NodeHandle node("~");
std::string host; int port;
node.param<std::string>("/warehouse_host", host, "");
node.param<int>("/warehouse_port", port, 0);
ROS_INFO("Connecting to warehouse on %s:%d", host.c_str(), port);
moveit_warehouse::RobotStateStorage rs(host, port);
std::vector<std::string> names;
rs.getKnownRobotStates(names);
if (names.empty())
ROS_INFO("There are no previously stored robot states");
else
{
ROS_INFO("Previously stored robot states:");
for (std::size_t i = 0 ; i < names.size() ; ++i)
ROS_INFO(" * %s", names[i].c_str());
}
boost::function<bool(moveit_msgs::SaveRobotStateToWarehouse::Request& request,
moveit_msgs::SaveRobotStateToWarehouse::Response& response)>
save_cb = boost::bind(&store_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::ListRobotStatesInWarehouse::Request& request,
moveit_msgs::ListRobotStatesInWarehouse::Response& response)>
list_cb = boost::bind(&list_states, _1, _2, &rs);
boost::function<bool(moveit_msgs::GetRobotStateFromWarehouse::Request& request,
moveit_msgs::GetRobotStateFromWarehouse::Response& response)>
get_cb = boost::bind(&get_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::CheckIfRobotStateExistsInWarehouse::Request& request,
moveit_msgs::CheckIfRobotStateExistsInWarehouse::Response& response)>
has_cb = boost::bind(&has_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::RenameRobotStateInWarehouse::Request& request,
moveit_msgs::RenameRobotStateInWarehouse::Response& response)>
rename_cb = boost::bind(&rename_state, _1, _2, &rs);
boost::function<bool(moveit_msgs::DeleteRobotStateFromWarehouse::Request& request,
moveit_msgs::DeleteRobotStateFromWarehouse::Response& response)>
delete_cb = boost::bind(&delete_state, _1, _2, &rs);
ros::ServiceServer save_state_server = node.advertiseService("save_robot_state", save_cb);
ros::ServiceServer list_states_server = node.advertiseService("list_robot_states", list_cb);
ros::ServiceServer get_state_server = node.advertiseService("get_robot_state", get_cb);
ros::ServiceServer has_state_server = node.advertiseService("has_robot_state", has_cb);
ros::ServiceServer rename_state_server = node.advertiseService("rename_robot_state", rename_cb);
ros::ServiceServer delete_state_server = node.advertiseService("delete_robot_state", delete_cb);
ros::waitForShutdown();
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Extended error message for OAuth2 (#148)<commit_after><|endoftext|>
|
<commit_before>//===- tools/seec-trace-view/StreamStatePanel.cpp -------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Clang/MappedProcessState.hpp"
#include "seec/Clang/MappedStateMovement.hpp"
#include "seec/Clang/MappedStreamState.hpp"
#include "seec/Util/ScopeExit.hpp"
#include "seec/wxWidgets/StringConversion.hpp"
#include <wx/listbook.h>
#include <wx/stc/stc.h>
#include "ActionRecord.hpp"
#include "ActionReplay.hpp"
#include "CommonMenus.hpp"
#include "ProcessMoveEvent.hpp"
#include "StateAccessToken.hpp"
#include "StreamStatePanel.hpp"
#include "SourceViewerSettings.hpp"
//===----------------------------------------------------------------------===//
// StreamPanel
//===----------------------------------------------------------------------===//
/// \brief Shows the contents of a single FILE stream.
///
class StreamPanel final : public wxPanel
{
/// Displays the data written to this FILE.
wxStyledTextCtrl *Text;
/// Parent's token for accessing the current state.
std::shared_ptr<StateAccessToken> &ParentAccess;
/// Pointer to the \c StreamState displayed by this \c StreamPanel.
seec::cm::StreamState const *State;
/// Character that the mouse is currently hovering over.
long MouseOverPosition;
/// Start of hover highlight range.
long HighlightStart;
/// Length of hover highlight range.
long HighlightLength;
/// Used to determine if a right-click was performed without moving.
bool ClickUnmoved;
/// \brief Clear highlighting used for mouse hover.
///
void clearHighlight() {
if (HighlightLength) {
Text->IndicatorClearRange(HighlightStart, HighlightLength);
HighlightStart = 0;
HighlightLength = 0;
}
}
/// \brief Updated the display using our current \c State.
///
void update() {
clearHighlight();
MouseOverPosition = wxSTC_INVALID_POSITION;
ClickUnmoved = false;
Text->SetReadOnly(false);
Text->SetValue(wxString{State->getWritten()});
Text->SetReadOnly(true);
Text->ScrollToEnd();
}
void OnTextMotion(wxMouseEvent &Ev) {
// When we exit this scope, call Event.Skip() so that it is handled by the
// default handler.
auto const SkipEvent = seec::scopeExit([&](){ Ev.Skip(); });
// Clear this in case we are inbetween right down and right up.
ClickUnmoved = false;
// Find the character that is being hovered over.
long Position;
auto const Test = Text->HitTest(Ev.GetPosition(), &Position);
if (Test != wxTE_HT_ON_TEXT
|| Position < 0
|| Position >= State->getWritten().size()
|| Position == MouseOverPosition)
return;
clearHighlight();
MouseOverPosition = Position;
// Highlight the write that we are hovering over.
auto const Write = State->getWriteAt(Position);
HighlightStart = Write.Begin;
HighlightLength = Write.End - Write.Begin;
Text->IndicatorFillRange(HighlightStart, HighlightLength);
}
void OnTextLeave(wxMouseEvent &Ev) {
MouseOverPosition = wxSTC_INVALID_POSITION;
clearHighlight();
}
void OnRightDown(wxMouseEvent &Ev) {
if (MouseOverPosition == wxSTC_INVALID_POSITION)
return;
ClickUnmoved = true;
Ev.Skip();
}
void OnRightUp(wxMouseEvent &Ev) {
if (!ClickUnmoved) {
Ev.Skip();
return;
}
wxMenu CM{};
BindMenuItem(
CM.Append(wxID_ANY,
seec::getwxStringExOrEmpty("TraceViewer",
(char const *[]){"ContextualNavigation",
"StreamRewindToWrite"})),
[this] (wxEvent &) -> void {
raiseMovementEvent(*this, ParentAccess,
[=] (seec::cm::ProcessState &ProcessState) -> bool {
return seec::cm::moveBackwardToStreamWriteAt(ProcessState,
*State,
MouseOverPosition);
});
});
PopupMenu(&CM);
}
public:
/// \brief Construct a new \c StreamPanel for a given \c StreamState.
///
StreamPanel(wxWindow *Parent,
std::shared_ptr<StateAccessToken> &WithParentAccess,
seec::cm::StreamState const &WithState)
: wxPanel(Parent),
Text(nullptr),
ParentAccess(WithParentAccess),
State(&WithState),
MouseOverPosition(wxSTC_INVALID_POSITION),
HighlightStart(0),
HighlightLength(0),
ClickUnmoved(false)
{
Text = new wxStyledTextCtrl(this, wxID_ANY);
Text->SetReadOnly(true);
// We only use one indicator (highlight), so set it here.
setupAllSciIndicatorTypes(*Text);
auto const Indicator = static_cast<int>(SciIndicatorType::CodeHighlight);
Text->SetIndicatorCurrent(Indicator);
Text->Bind(wxEVT_MOTION, &StreamPanel::OnTextMotion, this);
Text->Bind(wxEVT_LEAVE_WINDOW, &StreamPanel::OnTextLeave, this);
Text->Bind(wxEVT_RIGHT_DOWN, &StreamPanel::OnRightDown, this);
Text->Bind(wxEVT_RIGHT_UP, &StreamPanel::OnRightUp, this);
auto const Sizer = new wxBoxSizer(wxHORIZONTAL);
Sizer->Add(Text, wxSizerFlags().Proportion(1).Expand());
SetSizerAndFit(Sizer);
update();
}
/// \brief Update our \c StreamState.
///
void update(seec::cm::StreamState const &WithState)
{
State = &WithState;
update();
}
};
//===----------------------------------------------------------------------===//
// StreamStatePanel
//===----------------------------------------------------------------------===//
StreamStatePanel::StreamStatePanel()
: Book(nullptr),
Pages(),
Notifier(nullptr),
Recording(nullptr),
CurrentAccess()
{}
StreamStatePanel::StreamStatePanel(wxWindow *Parent,
ContextNotifier &WithNotifier,
ActionRecord &WithRecording,
ActionReplayFrame &WithReplay,
wxWindowID ID,
wxPoint const &Position,
wxSize const &Size)
: StreamStatePanel()
{
Create(Parent, WithNotifier, WithRecording, WithReplay, ID, Position, Size);
}
bool StreamStatePanel::Create(wxWindow *Parent,
ContextNotifier &WithNotifier,
ActionRecord &WithRecording,
ActionReplayFrame &WithReplay,
wxWindowID const ID,
wxPoint const &Position,
wxSize const &Size)
{
if (!wxPanel::Create(Parent, ID, Position, Size))
return false;
Notifier = &WithNotifier;
Recording = &WithRecording;
Book = new wxListbook(this, ID, Position, Size);
auto const Sizer = new wxBoxSizer(wxHORIZONTAL);
Sizer->Add(Book, wxSizerFlags().Proportion(1).Expand());
SetSizerAndFit(Sizer);
return true;
}
void StreamStatePanel::show(std::shared_ptr<StateAccessToken> Access,
seec::cm::ProcessState const &Process,
seec::cm::ThreadState const &Thread)
{
CurrentAccess = std::move(Access);
// Remove pages that no longer exist, update those that do.
for (auto It = Pages.begin(), End = Pages.end(); It != End; ++It) {
if (auto const StreamPtr = Process.getStream(It->first)) {
It->second->update(*StreamPtr);
}
else {
Pages.erase(It);
}
}
for (auto const &StreamEntry : Process.getStreams()) {
auto const Address = StreamEntry.first;
auto const It = Pages.lower_bound(Address);
// If this FILE doesn't have a page then create one.
if (It == Pages.end() || It->first != Address) {
auto const StreamPage = new StreamPanel(this,
CurrentAccess,
StreamEntry.second);
Book->AddPage(StreamPage, wxString{StreamEntry.second.getFilename()});
Pages.insert(It, std::make_pair(Address, StreamPage));
}
}
}
void StreamStatePanel::clear()
{
Book->DeleteAllPages();
Pages.clear();
}
<commit_msg>Fix comparison between signed and unsigned values.<commit_after>//===- tools/seec-trace-view/StreamStatePanel.cpp -------------------------===//
//
// SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//
#include "seec/Clang/MappedProcessState.hpp"
#include "seec/Clang/MappedStateMovement.hpp"
#include "seec/Clang/MappedStreamState.hpp"
#include "seec/Util/ScopeExit.hpp"
#include "seec/wxWidgets/StringConversion.hpp"
#include <wx/listbook.h>
#include <wx/stc/stc.h>
#include "ActionRecord.hpp"
#include "ActionReplay.hpp"
#include "CommonMenus.hpp"
#include "ProcessMoveEvent.hpp"
#include "StateAccessToken.hpp"
#include "StreamStatePanel.hpp"
#include "SourceViewerSettings.hpp"
//===----------------------------------------------------------------------===//
// StreamPanel
//===----------------------------------------------------------------------===//
/// \brief Shows the contents of a single FILE stream.
///
class StreamPanel final : public wxPanel
{
/// Displays the data written to this FILE.
wxStyledTextCtrl *Text;
/// Parent's token for accessing the current state.
std::shared_ptr<StateAccessToken> &ParentAccess;
/// Pointer to the \c StreamState displayed by this \c StreamPanel.
seec::cm::StreamState const *State;
/// Character that the mouse is currently hovering over.
long MouseOverPosition;
/// Start of hover highlight range.
long HighlightStart;
/// Length of hover highlight range.
long HighlightLength;
/// Used to determine if a right-click was performed without moving.
bool ClickUnmoved;
/// \brief Clear highlighting used for mouse hover.
///
void clearHighlight() {
if (HighlightLength) {
Text->IndicatorClearRange(HighlightStart, HighlightLength);
HighlightStart = 0;
HighlightLength = 0;
}
}
/// \brief Updated the display using our current \c State.
///
void update() {
clearHighlight();
MouseOverPosition = wxSTC_INVALID_POSITION;
ClickUnmoved = false;
Text->SetReadOnly(false);
Text->SetValue(wxString{State->getWritten()});
Text->SetReadOnly(true);
Text->ScrollToEnd();
}
void OnTextMotion(wxMouseEvent &Ev) {
// When we exit this scope, call Event.Skip() so that it is handled by the
// default handler.
auto const SkipEvent = seec::scopeExit([&](){ Ev.Skip(); });
// Clear this in case we are inbetween right down and right up.
ClickUnmoved = false;
// Find the character that is being hovered over.
long Position;
auto const Test = Text->HitTest(Ev.GetPosition(), &Position);
if (Test != wxTE_HT_ON_TEXT
|| Position < 0
|| static_cast<unsigned long>(Position) >= State->getWritten().size()
|| Position == MouseOverPosition)
return;
clearHighlight();
MouseOverPosition = Position;
// Highlight the write that we are hovering over.
auto const Write = State->getWriteAt(Position);
HighlightStart = Write.Begin;
HighlightLength = Write.End - Write.Begin;
Text->IndicatorFillRange(HighlightStart, HighlightLength);
}
void OnTextLeave(wxMouseEvent &Ev) {
MouseOverPosition = wxSTC_INVALID_POSITION;
clearHighlight();
}
void OnRightDown(wxMouseEvent &Ev) {
if (MouseOverPosition == wxSTC_INVALID_POSITION)
return;
ClickUnmoved = true;
Ev.Skip();
}
void OnRightUp(wxMouseEvent &Ev) {
if (!ClickUnmoved) {
Ev.Skip();
return;
}
wxMenu CM{};
BindMenuItem(
CM.Append(wxID_ANY,
seec::getwxStringExOrEmpty("TraceViewer",
(char const *[]){"ContextualNavigation",
"StreamRewindToWrite"})),
[this] (wxEvent &) -> void {
raiseMovementEvent(*this, ParentAccess,
[=] (seec::cm::ProcessState &ProcessState) -> bool {
return seec::cm::moveBackwardToStreamWriteAt(ProcessState,
*State,
MouseOverPosition);
});
});
PopupMenu(&CM);
}
public:
/// \brief Construct a new \c StreamPanel for a given \c StreamState.
///
StreamPanel(wxWindow *Parent,
std::shared_ptr<StateAccessToken> &WithParentAccess,
seec::cm::StreamState const &WithState)
: wxPanel(Parent),
Text(nullptr),
ParentAccess(WithParentAccess),
State(&WithState),
MouseOverPosition(wxSTC_INVALID_POSITION),
HighlightStart(0),
HighlightLength(0),
ClickUnmoved(false)
{
Text = new wxStyledTextCtrl(this, wxID_ANY);
Text->SetReadOnly(true);
// We only use one indicator (highlight), so set it here.
setupAllSciIndicatorTypes(*Text);
auto const Indicator = static_cast<int>(SciIndicatorType::CodeHighlight);
Text->SetIndicatorCurrent(Indicator);
Text->Bind(wxEVT_MOTION, &StreamPanel::OnTextMotion, this);
Text->Bind(wxEVT_LEAVE_WINDOW, &StreamPanel::OnTextLeave, this);
Text->Bind(wxEVT_RIGHT_DOWN, &StreamPanel::OnRightDown, this);
Text->Bind(wxEVT_RIGHT_UP, &StreamPanel::OnRightUp, this);
auto const Sizer = new wxBoxSizer(wxHORIZONTAL);
Sizer->Add(Text, wxSizerFlags().Proportion(1).Expand());
SetSizerAndFit(Sizer);
update();
}
/// \brief Update our \c StreamState.
///
void update(seec::cm::StreamState const &WithState)
{
State = &WithState;
update();
}
};
//===----------------------------------------------------------------------===//
// StreamStatePanel
//===----------------------------------------------------------------------===//
StreamStatePanel::StreamStatePanel()
: Book(nullptr),
Pages(),
Notifier(nullptr),
Recording(nullptr),
CurrentAccess()
{}
StreamStatePanel::StreamStatePanel(wxWindow *Parent,
ContextNotifier &WithNotifier,
ActionRecord &WithRecording,
ActionReplayFrame &WithReplay,
wxWindowID ID,
wxPoint const &Position,
wxSize const &Size)
: StreamStatePanel()
{
Create(Parent, WithNotifier, WithRecording, WithReplay, ID, Position, Size);
}
bool StreamStatePanel::Create(wxWindow *Parent,
ContextNotifier &WithNotifier,
ActionRecord &WithRecording,
ActionReplayFrame &WithReplay,
wxWindowID const ID,
wxPoint const &Position,
wxSize const &Size)
{
if (!wxPanel::Create(Parent, ID, Position, Size))
return false;
Notifier = &WithNotifier;
Recording = &WithRecording;
Book = new wxListbook(this, ID, Position, Size);
auto const Sizer = new wxBoxSizer(wxHORIZONTAL);
Sizer->Add(Book, wxSizerFlags().Proportion(1).Expand());
SetSizerAndFit(Sizer);
return true;
}
void StreamStatePanel::show(std::shared_ptr<StateAccessToken> Access,
seec::cm::ProcessState const &Process,
seec::cm::ThreadState const &Thread)
{
CurrentAccess = std::move(Access);
// Remove pages that no longer exist, update those that do.
for (auto It = Pages.begin(), End = Pages.end(); It != End; ++It) {
if (auto const StreamPtr = Process.getStream(It->first)) {
It->second->update(*StreamPtr);
}
else {
Pages.erase(It);
}
}
for (auto const &StreamEntry : Process.getStreams()) {
auto const Address = StreamEntry.first;
auto const It = Pages.lower_bound(Address);
// If this FILE doesn't have a page then create one.
if (It == Pages.end() || It->first != Address) {
auto const StreamPage = new StreamPanel(this,
CurrentAccess,
StreamEntry.second);
Book->AddPage(StreamPage, wxString{StreamEntry.second.getFilename()});
Pages.insert(It, std::make_pair(Address, StreamPage));
}
}
}
void StreamStatePanel::clear()
{
Book->DeleteAllPages();
Pages.clear();
}
<|endoftext|>
|
<commit_before>#pragma once
#include "declarations.hpp"
#include <gsl/gsl>
namespace mcpposutil
{
/**
* \brief Return start of data section.
**/
inline auto get_data_start() -> void *
{
return nullptr;
}
/**
* \brief Return end of data section.
**/
inline auto get_data_end() -> void *
{
return nullptr;
}
/**
* \brief Print current process map.
**/
inline void print_pmap(){};
}
<commit_msg>Fix OSX build<commit_after>#pragma once
#include "declarations.hpp"
#include <gsl/gsl>
namespace mcpposutil
{
/**
* \brief Return start of data section.
**/
inline auto get_data_start() -> void *
{
return nullptr;
}
/**
* \brief Return end of data section.
**/
inline auto get_data_end() -> void *
{
return nullptr;
}
/**
* \brief Print current process map.
**/
inline ::std::string pmap_as_string() { return {}; };
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/invalidation_notifier.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/sync/notifier/invalidation_version_tracker.h"
#include "chrome/browser/sync/notifier/mock_sync_notifier_observer.h"
#include "jingle/notifier/base/fake_base_task.h"
#include "jingle/notifier/base/notifier_options.h"
#include "net/base/cert_verifier.h"
#include "net/base/host_resolver.h"
#include "net/url_request/url_request_test_util.h"
#include "sync/syncable/model_type.h"
#include "sync/syncable/model_type_payload_map.h"
#include "sync/util/weak_handle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sync_notifier {
namespace {
using ::testing::InSequence;
using ::testing::StrictMock;
class InvalidationNotifierTest : public testing::Test {
protected:
virtual void SetUp() {
notifier::NotifierOptions notifier_options;
// Note: URLRequestContextGetters are ref-counted.
notifier_options.request_context_getter =
new TestURLRequestContextGetter(message_loop_.message_loop_proxy());
invalidation_notifier_.reset(
new InvalidationNotifier(
notifier_options,
InvalidationVersionMap(),
browser_sync::MakeWeakHandle(
base::WeakPtr<InvalidationVersionTracker>()),
"fake_client_info"));
invalidation_notifier_->AddObserver(&mock_observer_);
}
virtual void TearDown() {
invalidation_notifier_->RemoveObserver(&mock_observer_);
// Stopping the invalidation notifier stops its scheduler, which deletes any
// pending tasks without running them. Some tasks "run and delete" another
// task, so they must be run in order to avoid leaking the inner task.
// Stopping does not schedule any tasks, so it's both necessary and
// sufficient to drain the task queue before stopping the notifier.
message_loop_.RunAllPending();
invalidation_notifier_.reset();
}
MessageLoopForIO message_loop_;
scoped_ptr<InvalidationNotifier> invalidation_notifier_;
StrictMock<MockSyncNotifierObserver> mock_observer_;
notifier::FakeBaseTask fake_base_task_;
};
TEST_F(InvalidationNotifierTest, Basic) {
InSequence dummy;
syncable::ModelTypePayloadMap type_payloads;
type_payloads[syncable::PREFERENCES] = "payload";
type_payloads[syncable::BOOKMARKS] = "";
type_payloads[syncable::AUTOFILL] = "";
EXPECT_CALL(mock_observer_, OnNotificationStateChange(true));
EXPECT_CALL(mock_observer_, StoreState("new_fake_state"));
EXPECT_CALL(mock_observer_,
OnIncomingNotification(type_payloads,
REMOTE_NOTIFICATION));
EXPECT_CALL(mock_observer_, OnNotificationStateChange(false));
invalidation_notifier_->SetState("fake_state");
invalidation_notifier_->SetUniqueId("fake_id");
invalidation_notifier_->UpdateCredentials("foo@bar.com", "fake_token");
invalidation_notifier_->OnConnect(fake_base_task_.AsWeakPtr());
invalidation_notifier_->OnSessionStatusChanged(true);
invalidation_notifier_->WriteState("new_fake_state");
invalidation_notifier_->OnInvalidate(type_payloads);
// Shouldn't trigger notification state change.
invalidation_notifier_->OnDisconnect();
invalidation_notifier_->OnConnect(fake_base_task_.AsWeakPtr());
invalidation_notifier_->OnSessionStatusChanged(false);
}
} // namespace
} // namespace sync_notifier
<commit_msg>Revert 127587 - [Sync] Fix racy failure in invalidation_notifier_unittest.cc<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync/notifier/invalidation_notifier.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/sync/notifier/invalidation_version_tracker.h"
#include "chrome/browser/sync/notifier/mock_sync_notifier_observer.h"
#include "jingle/notifier/base/fake_base_task.h"
#include "jingle/notifier/base/notifier_options.h"
#include "net/base/cert_verifier.h"
#include "net/base/host_resolver.h"
#include "net/url_request/url_request_test_util.h"
#include "sync/syncable/model_type.h"
#include "sync/syncable/model_type_payload_map.h"
#include "sync/util/weak_handle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sync_notifier {
namespace {
using ::testing::InSequence;
using ::testing::StrictMock;
class InvalidationNotifierTest : public testing::Test {
protected:
virtual void SetUp() {
notifier::NotifierOptions notifier_options;
// Note: URLRequestContextGetters are ref-counted.
notifier_options.request_context_getter =
new TestURLRequestContextGetter(message_loop_.message_loop_proxy());
invalidation_notifier_.reset(
new InvalidationNotifier(
notifier_options,
InvalidationVersionMap(),
browser_sync::MakeWeakHandle(
base::WeakPtr<InvalidationVersionTracker>()),
"fake_client_info"));
invalidation_notifier_->AddObserver(&mock_observer_);
}
virtual void TearDown() {
invalidation_notifier_->RemoveObserver(&mock_observer_);
// Stopping the invalidation notifier stops its scheduler, which deletes any
// pending tasks without running them. Some tasks "run and delete" another
// task, so they must be run in order to avoid leaking the inner task.
// Stopping does not schedule any tasks, so it's both necessary and
// sufficient to drain the task queue before stopping the notifier.
message_loop_.RunAllPending();
invalidation_notifier_.reset();
}
MessageLoop message_loop_;
scoped_ptr<InvalidationNotifier> invalidation_notifier_;
StrictMock<MockSyncNotifierObserver> mock_observer_;
notifier::FakeBaseTask fake_base_task_;
};
TEST_F(InvalidationNotifierTest, Basic) {
InSequence dummy;
syncable::ModelTypePayloadMap type_payloads;
type_payloads[syncable::PREFERENCES] = "payload";
type_payloads[syncable::BOOKMARKS] = "";
type_payloads[syncable::AUTOFILL] = "";
EXPECT_CALL(mock_observer_, OnNotificationStateChange(true));
EXPECT_CALL(mock_observer_, StoreState("new_fake_state"));
EXPECT_CALL(mock_observer_,
OnIncomingNotification(type_payloads,
REMOTE_NOTIFICATION));
EXPECT_CALL(mock_observer_, OnNotificationStateChange(false));
invalidation_notifier_->SetState("fake_state");
invalidation_notifier_->SetUniqueId("fake_id");
invalidation_notifier_->UpdateCredentials("foo@bar.com", "fake_token");
invalidation_notifier_->OnConnect(fake_base_task_.AsWeakPtr());
invalidation_notifier_->OnSessionStatusChanged(true);
invalidation_notifier_->WriteState("new_fake_state");
invalidation_notifier_->OnInvalidate(type_payloads);
// Shouldn't trigger notification state change.
invalidation_notifier_->OnDisconnect();
invalidation_notifier_->OnConnect(fake_base_task_.AsWeakPtr());
invalidation_notifier_->OnSessionStatusChanged(false);
}
} // namespace
} // namespace sync_notifier
<|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 "base/json/json_reader.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/apps_promo.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/web_resource/promo_resource_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/testing_pref_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
typedef testing::Test PromoResourceServiceTest;
// Verifies that custom dates read from a web resource server are written to
// the preferences file.
TEST_F(PromoResourceServiceTest, UnpackLogoSignal) {
// Set up a testing profile and create a promo resource service.
TestingProfile profile;
TestingPrefService local_state;
TestingBrowserProcess* testing_browser_process =
static_cast<TestingBrowserProcess*>(g_browser_process);
testing_browser_process->SetPrefService(&local_state);
browser::RegisterLocalState(&local_state);
scoped_refptr<PromoResourceService> web_resource_service(
new PromoResourceService(&profile));
// Set up start and end dates in a Dictionary as if parsed from the service.
std::string json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" \"name\": \"custom_logo_start\","
" \"inproduct\": \"31/01/10 01:00 GMT\""
" },"
" {"
" \"name\": \"custom_logo_end\","
" \"inproduct\": \"31/01/12 01:00 GMT\""
" }"
" ]"
" }"
"}";
scoped_ptr<DictionaryValue> test_json(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Check that prefs are set correctly.
web_resource_service->UnpackLogoSignal(*(test_json.get()));
PrefService* prefs = profile.GetPrefs();
ASSERT_TRUE(prefs != NULL);
double logo_start =
prefs->GetDouble(prefs::kNTPCustomLogoStart);
EXPECT_EQ(logo_start, 1264899600); // unix epoch for Jan 31 2010 0100 GMT.
double logo_end =
prefs->GetDouble(prefs::kNTPCustomLogoEnd);
EXPECT_EQ(logo_end, 1327971600); // unix epoch for Jan 31 2012 0100 GMT.
// Change the start only and recheck.
json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" \"name\": \"custom_logo_start\","
" \"inproduct\": \"28/02/10 14:00 GMT\""
" },"
" {"
" \"name\": \"custom_logo_end\","
" \"inproduct\": \"31/01/12 01:00 GMT\""
" }"
" ]"
" }"
"}";
test_json->Clear();
test_json.reset(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Check that prefs are set correctly.
web_resource_service->UnpackLogoSignal(*(test_json.get()));
logo_start = prefs->GetDouble(prefs::kNTPCustomLogoStart);
EXPECT_EQ(logo_start, 1267365600); // date changes to Feb 28 2010 1400 GMT.
// If no date is included in the prefs, reset custom logo dates to 0.
json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" }"
" ]"
" }"
"}";
test_json->Clear();
test_json.reset(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Check that prefs are set correctly.
web_resource_service->UnpackLogoSignal(*(test_json.get()));
logo_start = prefs->GetDouble(prefs::kNTPCustomLogoStart);
EXPECT_EQ(logo_start, 0); // date value reset to 0;
logo_end = prefs->GetDouble(prefs::kNTPCustomLogoEnd);
EXPECT_EQ(logo_end, 0); // date value reset to 0;
}
TEST_F(PromoResourceServiceTest, UnpackPromoSignal) {
// Set up a testing profile and create a promo resource service.
TestingProfile profile;
TestingPrefService local_state;
TestingBrowserProcess* testing_browser_process =
static_cast<TestingBrowserProcess*>(g_browser_process);
testing_browser_process->SetPrefService(&local_state);
browser::RegisterLocalState(&local_state);
scoped_refptr<PromoResourceService> web_resource_service(
new PromoResourceService(&profile));
// Set up start and end dates and promo line in a Dictionary as if parsed
// from the service.
std::string json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" \"name\": \"promo_start\","
" \"question\": \"3:2\","
" \"tooltip\": \"Eat more pie!\","
" \"inproduct\": \"31/01/10 01:00 GMT\""
" },"
" {"
" \"name\": \"promo_end\","
" \"inproduct\": \"31/01/12 01:00 GMT\""
" }"
" ]"
" }"
"}";
scoped_ptr<DictionaryValue> test_json(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Initialize a message loop for this to run on.
MessageLoop loop;
// Check that prefs are set correctly.
web_resource_service->UnpackPromoSignal(*(test_json.get()));
PrefService* prefs = profile.GetPrefs();
ASSERT_TRUE(prefs != NULL);
std::string promo_line = prefs->GetString(prefs::kNTPPromoLine);
EXPECT_EQ(promo_line, "Eat more pie!");
int promo_group = prefs->GetInteger(prefs::kNTPPromoGroup);
EXPECT_GE(promo_group, 0);
EXPECT_LT(promo_group, 16);
int promo_build_type = prefs->GetInteger(prefs::kNTPPromoBuild);
EXPECT_EQ(promo_build_type & PromoResourceService::DEV_BUILD,
PromoResourceService::DEV_BUILD);
EXPECT_EQ(promo_build_type & PromoResourceService::BETA_BUILD,
PromoResourceService::BETA_BUILD);
EXPECT_EQ(promo_build_type & PromoResourceService::STABLE_BUILD, 0);
int promo_time_slice = prefs->GetInteger(prefs::kNTPPromoGroupTimeSlice);
EXPECT_EQ(promo_time_slice, 2);
double promo_start =
prefs->GetDouble(prefs::kNTPPromoStart);
int64 actual_start = 1264899600 + // unix epoch for Jan 31 2010 0100 GMT.
promo_group * 2 * 60 * 60;
EXPECT_EQ(promo_start, actual_start);
double promo_end =
prefs->GetDouble(prefs::kNTPPromoEnd);
EXPECT_EQ(promo_end, 1327971600); // unix epoch for Jan 31 2012 0100 GMT.
}
TEST_F(PromoResourceServiceTest, UnpackWebStoreSignal) {
// Set up a testing profile and create a promo resource service.
TestingProfile profile;
TestingPrefService local_state;
TestingBrowserProcess* testing_browser_process =
static_cast<TestingBrowserProcess*>(g_browser_process);
testing_browser_process->SetPrefService(&local_state);
browser::RegisterLocalState(&local_state);
scoped_refptr<PromoResourceService> web_resource_service(
new PromoResourceService(&profile));
web_resource_service->set_channel("dev");
// Set up start and end dates and promo line in a Dictionary as if parsed
// from the service.
std::string json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" \"answer_id\": \"341252\","
" \"name\": \"webstore_promo:15\","
" \"question\": \"The header!\","
" \"inproduct_target\": \"The button label!\","
" \"inproduct\": \"http://link.com\","
" \"tooltip\": \"No thanks, hide this.\""
" }"
" ]"
" }"
"}";
scoped_ptr<DictionaryValue> test_json(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Initialize a message loop for this to run on.
MessageLoop loop;
// Check that prefs are set correctly.
web_resource_service->UnpackWebStoreSignal(*(test_json.get()));
PrefService* prefs = profile.GetPrefs();
ASSERT_TRUE(prefs != NULL);
EXPECT_EQ("341252", AppsPromo::GetPromoId());
EXPECT_EQ("The header!", AppsPromo::GetPromoHeaderText());
EXPECT_EQ("The button label!", AppsPromo::GetPromoButtonText());
EXPECT_EQ(GURL("http://link.com"), AppsPromo::GetPromoLink());
EXPECT_EQ("No thanks, hide this.", AppsPromo::GetPromoExpireText());
}
TEST_F(PromoResourceServiceTest, IsBuildTargeted) {
// canary
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("canary", 1));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("canary", 3));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("canary", 7));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("canary", 15));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("canary", 8));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("canary", 11));
// dev
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 1));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 3));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 7));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 15));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("dev", 8));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 11));
// beta
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("beta", 1));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("beta", 3));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("beta", 7));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("beta", 15));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("beta", 8));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("beta", 11));
// stable
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("", 1));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("", 3));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("", 7));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("", 15));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("", 8));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("", 11));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("", 12));
}
<commit_msg>Fix chromeos unit tests by cleaning up the local state in PromoResourceServiceTest.<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 "base/json/json_reader.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/extensions/apps_promo.h"
#include "chrome/browser/prefs/browser_prefs.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/web_resource/promo_resource_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_browser_process.h"
#include "chrome/test/testing_pref_service.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"
typedef testing::Test PromoResourceServiceTest;
// Verifies that custom dates read from a web resource server are written to
// the preferences file.
TEST_F(PromoResourceServiceTest, UnpackLogoSignal) {
// Set up a testing profile and create a promo resource service.
TestingProfile profile;
TestingPrefService local_state;
TestingBrowserProcess* testing_browser_process =
static_cast<TestingBrowserProcess*>(g_browser_process);
testing_browser_process->SetPrefService(&local_state);
browser::RegisterLocalState(&local_state);
scoped_refptr<PromoResourceService> web_resource_service(
new PromoResourceService(&profile));
// Set up start and end dates in a Dictionary as if parsed from the service.
std::string json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" \"name\": \"custom_logo_start\","
" \"inproduct\": \"31/01/10 01:00 GMT\""
" },"
" {"
" \"name\": \"custom_logo_end\","
" \"inproduct\": \"31/01/12 01:00 GMT\""
" }"
" ]"
" }"
"}";
scoped_ptr<DictionaryValue> test_json(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Check that prefs are set correctly.
web_resource_service->UnpackLogoSignal(*(test_json.get()));
PrefService* prefs = profile.GetPrefs();
ASSERT_TRUE(prefs != NULL);
double logo_start =
prefs->GetDouble(prefs::kNTPCustomLogoStart);
EXPECT_EQ(logo_start, 1264899600); // unix epoch for Jan 31 2010 0100 GMT.
double logo_end =
prefs->GetDouble(prefs::kNTPCustomLogoEnd);
EXPECT_EQ(logo_end, 1327971600); // unix epoch for Jan 31 2012 0100 GMT.
// Change the start only and recheck.
json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" \"name\": \"custom_logo_start\","
" \"inproduct\": \"28/02/10 14:00 GMT\""
" },"
" {"
" \"name\": \"custom_logo_end\","
" \"inproduct\": \"31/01/12 01:00 GMT\""
" }"
" ]"
" }"
"}";
test_json->Clear();
test_json.reset(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Check that prefs are set correctly.
web_resource_service->UnpackLogoSignal(*(test_json.get()));
logo_start = prefs->GetDouble(prefs::kNTPCustomLogoStart);
EXPECT_EQ(logo_start, 1267365600); // date changes to Feb 28 2010 1400 GMT.
// If no date is included in the prefs, reset custom logo dates to 0.
json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" }"
" ]"
" }"
"}";
test_json->Clear();
test_json.reset(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Check that prefs are set correctly.
web_resource_service->UnpackLogoSignal(*(test_json.get()));
logo_start = prefs->GetDouble(prefs::kNTPCustomLogoStart);
EXPECT_EQ(logo_start, 0); // date value reset to 0;
logo_end = prefs->GetDouble(prefs::kNTPCustomLogoEnd);
EXPECT_EQ(logo_end, 0); // date value reset to 0;
testing_browser_process->SetPrefService(NULL);
}
TEST_F(PromoResourceServiceTest, UnpackPromoSignal) {
// Set up a testing profile and create a promo resource service.
TestingProfile profile;
TestingPrefService local_state;
TestingBrowserProcess* testing_browser_process =
static_cast<TestingBrowserProcess*>(g_browser_process);
testing_browser_process->SetPrefService(&local_state);
browser::RegisterLocalState(&local_state);
scoped_refptr<PromoResourceService> web_resource_service(
new PromoResourceService(&profile));
// Set up start and end dates and promo line in a Dictionary as if parsed
// from the service.
std::string json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" \"name\": \"promo_start\","
" \"question\": \"3:2\","
" \"tooltip\": \"Eat more pie!\","
" \"inproduct\": \"31/01/10 01:00 GMT\""
" },"
" {"
" \"name\": \"promo_end\","
" \"inproduct\": \"31/01/12 01:00 GMT\""
" }"
" ]"
" }"
"}";
scoped_ptr<DictionaryValue> test_json(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Initialize a message loop for this to run on.
MessageLoop loop;
// Check that prefs are set correctly.
web_resource_service->UnpackPromoSignal(*(test_json.get()));
PrefService* prefs = profile.GetPrefs();
ASSERT_TRUE(prefs != NULL);
std::string promo_line = prefs->GetString(prefs::kNTPPromoLine);
EXPECT_EQ(promo_line, "Eat more pie!");
int promo_group = prefs->GetInteger(prefs::kNTPPromoGroup);
EXPECT_GE(promo_group, 0);
EXPECT_LT(promo_group, 16);
int promo_build_type = prefs->GetInteger(prefs::kNTPPromoBuild);
EXPECT_EQ(promo_build_type & PromoResourceService::DEV_BUILD,
PromoResourceService::DEV_BUILD);
EXPECT_EQ(promo_build_type & PromoResourceService::BETA_BUILD,
PromoResourceService::BETA_BUILD);
EXPECT_EQ(promo_build_type & PromoResourceService::STABLE_BUILD, 0);
int promo_time_slice = prefs->GetInteger(prefs::kNTPPromoGroupTimeSlice);
EXPECT_EQ(promo_time_slice, 2);
double promo_start =
prefs->GetDouble(prefs::kNTPPromoStart);
int64 actual_start = 1264899600 + // unix epoch for Jan 31 2010 0100 GMT.
promo_group * 2 * 60 * 60;
EXPECT_EQ(promo_start, actual_start);
double promo_end =
prefs->GetDouble(prefs::kNTPPromoEnd);
EXPECT_EQ(promo_end, 1327971600); // unix epoch for Jan 31 2012 0100 GMT.
testing_browser_process->SetPrefService(NULL);
}
TEST_F(PromoResourceServiceTest, UnpackWebStoreSignal) {
// Set up a testing profile and create a promo resource service.
TestingProfile profile;
TestingPrefService local_state;
TestingBrowserProcess* testing_browser_process =
static_cast<TestingBrowserProcess*>(g_browser_process);
testing_browser_process->SetPrefService(&local_state);
browser::RegisterLocalState(&local_state);
scoped_refptr<PromoResourceService> web_resource_service(
new PromoResourceService(&profile));
web_resource_service->set_channel("dev");
// Set up start and end dates and promo line in a Dictionary as if parsed
// from the service.
std::string json = "{ "
" \"topic\": {"
" \"answers\": ["
" {"
" \"answer_id\": \"341252\","
" \"name\": \"webstore_promo:15\","
" \"question\": \"The header!\","
" \"inproduct_target\": \"The button label!\","
" \"inproduct\": \"http://link.com\","
" \"tooltip\": \"No thanks, hide this.\""
" }"
" ]"
" }"
"}";
scoped_ptr<DictionaryValue> test_json(static_cast<DictionaryValue*>(
base::JSONReader::Read(json, false)));
// Initialize a message loop for this to run on.
MessageLoop loop;
// Check that prefs are set correctly.
web_resource_service->UnpackWebStoreSignal(*(test_json.get()));
PrefService* prefs = profile.GetPrefs();
ASSERT_TRUE(prefs != NULL);
EXPECT_EQ("341252", AppsPromo::GetPromoId());
EXPECT_EQ("The header!", AppsPromo::GetPromoHeaderText());
EXPECT_EQ("The button label!", AppsPromo::GetPromoButtonText());
EXPECT_EQ(GURL("http://link.com"), AppsPromo::GetPromoLink());
EXPECT_EQ("No thanks, hide this.", AppsPromo::GetPromoExpireText());
testing_browser_process->SetPrefService(NULL);
}
TEST_F(PromoResourceServiceTest, IsBuildTargeted) {
// canary
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("canary", 1));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("canary", 3));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("canary", 7));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("canary", 15));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("canary", 8));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("canary", 11));
// dev
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 1));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 3));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 7));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 15));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("dev", 8));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("dev", 11));
// beta
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("beta", 1));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("beta", 3));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("beta", 7));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("beta", 15));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("beta", 8));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("beta", 11));
// stable
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("", 1));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("", 3));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("", 7));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("", 15));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("", 8));
EXPECT_FALSE(PromoResourceService::IsBuildTargeted("", 11));
EXPECT_TRUE(PromoResourceService::IsBuildTargeted("", 12));
}
<|endoftext|>
|
<commit_before>#ifndef RECURSE_BODYPARSER_HPP
#define RECURSE_BODYPARSER_HPP
#include <QJsonDocument>
#include <QJsonObject>
auto bodyparser()
{
return [](auto &req, auto &res, auto next) {
if (req.body.isEmpty())
return next();
if (req.header["content-type"] == "application/json") {
QJsonDocument json = QJsonDocument::fromJson(req.body.toUtf8());
const QVariantMap map = json.object().toVariantMap();
QMap<QString, QVariant>::const_iterator i;
for (i = map.constBegin(); i != map.constEnd(); ++i) {
req.body_ph[i.key()] = i.value();
}
}
else if (req.header["content-type"] == "application/x-www-form-urlencoded") {
}
next();
};
}
#endif // RECURSE_BODYPARSER_HPP
<commit_msg>use req.body_parsed instead of req.body_ph<commit_after>#ifndef RECURSE_BODYPARSER_HPP
#define RECURSE_BODYPARSER_HPP
#include <QJsonDocument>
#include <QJsonObject>
auto bodyparser()
{
return [](auto &req, auto &res, auto next) {
if (req.body.isEmpty())
return next();
if (req.header["content-type"] == "application/json") {
QJsonDocument json = QJsonDocument::fromJson(req.body.toUtf8());
const QVariantMap map = json.object().toVariantMap();
QMap<QString, QVariant>::const_iterator i;
for (i = map.constBegin(); i != map.constEnd(); ++i) {
req.body_parsed[i.key()] = i.value();
}
}
else if (req.header["content-type"] == "application/x-www-form-urlencoded") {
}
next();
};
}
#endif // RECURSE_BODYPARSER_HPP
<|endoftext|>
|
<commit_before>// Copyright 2020 Global Phasing Ltd.
//
// Reindex merged or unmerged MTZ file.
// TODO: handle operations that results in non-integral indices.
#include <cstdio>
#include <cstring> // for strpbrk
#include <algorithm>
#ifndef GEMMI_ALL_IN_ONE
# define GEMMI_WRITE_IMPLEMENTATION 1
#endif
#include <gemmi/mtz.hpp>
#include <gemmi/gz.hpp> // for MaybeGzipped
#include <gemmi/version.hpp> // for GEMMI_VERSION
#define GEMMI_PROG reindex
#include "options.h"
using std::fprintf;
namespace {
enum OptionIndex { Hkl=4, NoHistory, NoSort };
const option::Descriptor Usage[] = {
{ NoOp, 0, "", "", Arg::None,
"Usage:\n " EXE_NAME " [options] INPUT_MTZ OUTPUT_MTZ"
"\nOptions:"},
CommonUsage[Help],
CommonUsage[Version],
CommonUsage[Verbose],
{ Hkl, 0, "", "hkl", Arg::Required,
" --hkl=OP \tReindexing transform as triplet (e.g. k,h,-l)." },
{ NoHistory, 0, "", "no-history", Arg::None,
" --no-history \tDo not add 'Reindexed with...' line to mtz HISTORY." },
{ NoSort, 0, "", "no-sort", Arg::None,
" --no-sort \tDo not reorder reflections." },
{ NoOp, 0, "", "", Arg::None,
"\nInput file can be gzipped." },
{ 0, 0, 0, 0, 0, 0 }
};
} // anonymous namespace
int GEMMI_MAIN(int argc, char **argv) {
OptParser p(EXE_NAME);
p.simple_parse(argc, argv, Usage);
p.require_positional_args(2);
bool verbose = p.options[Verbose];
const char* input_path = p.nonOption(0);
const char* output_path = p.nonOption(1);
if (!p.options[Hkl]) {
fprintf(stderr, "Specify transform with option --hkl\n");
return 1;
}
const char* hkl_arg = p.options[Hkl].arg;
gemmi::Op op = gemmi::parse_triplet(hkl_arg);
if (std::strpbrk(hkl_arg, "xyzabcXYZABC"))
gemmi::fail("specify OP in terms of h, k and l");
if (op.tran != gemmi::Op::Tran{{0, 0, 0}})
gemmi::fail("reindexing operator should not have a translation");
// transpose rotation
gemmi::Op real_space_op{op.transposed_rot(), {0, 0, 0}};
if (verbose)
fprintf(stderr, "real space transformation: %s\n", real_space_op.triplet().c_str());
gemmi::Mtz mtz;
if (verbose) {
fprintf(stderr, "Reading %s ...\n", input_path);
mtz.warnings = stderr;
}
try {
mtz.read_input(gemmi::MaybeGzipped(input_path), true);
mtz.switch_to_original_hkl();
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR reading %s: %s\n", input_path, e.what());
return 1;
}
// reindex
for (size_t n = 0; n < mtz.data.size(); n += mtz.columns.size())
mtz.set_hkl(n, real_space_op.apply_to_hkl(mtz.get_hkl(n)));
// hand change requires data modification
if (op.det_rot() < 0)
for (gemmi::Mtz::Column& column : mtz.columns) {
// negate anomalous difference
if (column.type == 'D') {
for (float& value : column)
value = -value;
if (verbose)
fprintf(stderr, "Column %s: anomalous difference negated.\n",
column.label.c_str());
continue;
}
// swap (+) and (-)
size_t pos = column.label.find("(+)");
if (pos != std::string::npos) {
std::string minus_label = column.label;
minus_label[pos+1] = '-';
gemmi::Mtz::Column* minus_column =
mtz.column_with_label(minus_label, &column.dataset());
if (minus_column) {
for (size_t n = 0; n < mtz.data.size(); n += mtz.columns.size())
std::swap(mtz.data[n + column.idx],
mtz.data[n + minus_column->idx]);
if (verbose)
fprintf(stderr, "Swapped values from %s and %s.\n",
column.label.c_str(), minus_label.c_str());
} else {
fprintf(stderr, "Warning: matching pair not found for: %s\n",
column.label.c_str());
}
}
}
// change space group
mtz.spacegroup = gemmi::find_spacegroup_by_change_of_basis(mtz.spacegroup, op.inverse());
if (mtz.spacegroup) {
if (verbose)
fprintf(stderr, "Space group changed from %s to %s\n.",
mtz.spacegroup_name.c_str(), mtz.spacegroup->xhm().c_str());
} else {
fprintf(stderr, "WARNING: new space group name could not be determined.\n");
}
if (mtz.is_merged())
mtz.ensure_asu();
else
mtz.switch_to_asu_hkl();
if (!p.options[NoSort])
mtz.sort();
if (!p.options[NoHistory])
mtz.history.emplace(mtz.history.begin(),
"Reindexed with gemmi-reindex " GEMMI_VERSION);
if (verbose)
fprintf(stderr, "Writing %s ...\n", output_path);
mtz.write_to_file(output_path);
return 0;
}
// vim:sw=2:ts=2:et:path^=../include,../third_party
<commit_msg>reindex: change unit cell<commit_after>// Copyright 2020 Global Phasing Ltd.
//
// Reindex merged or unmerged MTZ file.
// TODO: handle operations that results in non-integral indices.
#include <cstdio>
#include <cstring> // for strpbrk
#include <algorithm>
#ifndef GEMMI_ALL_IN_ONE
# define GEMMI_WRITE_IMPLEMENTATION 1
#endif
#include <gemmi/mtz.hpp>
#include <gemmi/gz.hpp> // for MaybeGzipped
#include <gemmi/version.hpp> // for GEMMI_VERSION
#define GEMMI_PROG reindex
#include "options.h"
using std::fprintf;
namespace {
enum OptionIndex { Hkl=4, NoHistory, NoSort };
const option::Descriptor Usage[] = {
{ NoOp, 0, "", "", Arg::None,
"Usage:\n " EXE_NAME " [options] INPUT_MTZ OUTPUT_MTZ"
"\nOptions:"},
CommonUsage[Help],
CommonUsage[Version],
CommonUsage[Verbose],
{ Hkl, 0, "", "hkl", Arg::Required,
" --hkl=OP \tReindexing transform as triplet (e.g. k,h,-l)." },
{ NoHistory, 0, "", "no-history", Arg::None,
" --no-history \tDo not add 'Reindexed with...' line to mtz HISTORY." },
{ NoSort, 0, "", "no-sort", Arg::None,
" --no-sort \tDo not reorder reflections." },
{ NoOp, 0, "", "", Arg::None,
"\nInput file can be gzipped." },
{ 0, 0, 0, 0, 0, 0 }
};
} // anonymous namespace
int GEMMI_MAIN(int argc, char **argv) {
OptParser p(EXE_NAME);
p.simple_parse(argc, argv, Usage);
p.require_positional_args(2);
bool verbose = p.options[Verbose];
const char* input_path = p.nonOption(0);
const char* output_path = p.nonOption(1);
if (!p.options[Hkl]) {
fprintf(stderr, "Specify transform with option --hkl\n");
return 1;
}
const char* hkl_arg = p.options[Hkl].arg;
gemmi::Op op = gemmi::parse_triplet(hkl_arg);
if (std::strpbrk(hkl_arg, "xyzabcXYZABC"))
gemmi::fail("specify OP in terms of h, k and l");
if (op.tran != gemmi::Op::Tran{{0, 0, 0}})
gemmi::fail("reindexing operator should not have a translation");
// transpose rotation
// TODO: it may be wrong if op.rot is not a rotation matrix,
// i.e. when cell volume changes
gemmi::Op real_space_op{op.transposed_rot(), {0, 0, 0}};
if (verbose)
fprintf(stderr, "real space transformation: %s\n", real_space_op.triplet().c_str());
gemmi::Mtz mtz;
if (verbose) {
fprintf(stderr, "Reading %s ...\n", input_path);
mtz.warnings = stderr;
}
try {
mtz.read_input(gemmi::MaybeGzipped(input_path), true);
mtz.switch_to_original_hkl();
} catch (std::runtime_error& e) {
fprintf(stderr, "ERROR reading %s: %s\n", input_path, e.what());
return 1;
}
// reindex
for (size_t n = 0; n < mtz.data.size(); n += mtz.columns.size())
mtz.set_hkl(n, real_space_op.apply_to_hkl(mtz.get_hkl(n)));
// hand change requires data modification
if (op.det_rot() < 0)
for (gemmi::Mtz::Column& column : mtz.columns) {
// negate anomalous difference
if (column.type == 'D') {
for (float& value : column)
value = -value;
if (verbose)
fprintf(stderr, "Column %s: anomalous difference negated.\n",
column.label.c_str());
continue;
}
// swap (+) and (-)
size_t pos = column.label.find("(+)");
if (pos != std::string::npos) {
std::string minus_label = column.label;
minus_label[pos+1] = '-';
gemmi::Mtz::Column* minus_column =
mtz.column_with_label(minus_label, &column.dataset());
if (minus_column) {
for (size_t n = 0; n < mtz.data.size(); n += mtz.columns.size())
std::swap(mtz.data[n + column.idx],
mtz.data[n + minus_column->idx]);
if (verbose)
fprintf(stderr, "Swapped values from %s and %s.\n",
column.label.c_str(), minus_label.c_str());
} else {
fprintf(stderr, "Warning: matching pair not found for: %s\n",
column.label.c_str());
}
}
}
// change space group
mtz.spacegroup = gemmi::find_spacegroup_by_change_of_basis(mtz.spacegroup, op.inverse());
if (mtz.spacegroup) {
if (verbose)
fprintf(stderr, "Space group changed from %s to %s\n.",
mtz.spacegroup_name.c_str(), mtz.spacegroup->xhm().c_str());
} else {
fprintf(stderr, "WARNING: new space group name could not be determined.\n");
}
// change unit cell
// TODO: change each unit cell separately, including batch headers
gemmi::Mat33 mat = mtz.cell.orth.mat.multiply(gemmi::rot_as_mat33(real_space_op));
gemmi::UnitCell new_cell;
new_cell.set_from_vectors(mat.column_copy(0), mat.column_copy(1), mat.column_copy(2));
mtz.set_cell_for_all(new_cell);
mat = mtz.cell.orth.mat;
if (mtz.is_merged())
mtz.ensure_asu();
else
mtz.switch_to_asu_hkl();
if (!p.options[NoSort])
mtz.sort();
if (!p.options[NoHistory])
mtz.history.emplace(mtz.history.begin(),
"Reindexed with gemmi-reindex " GEMMI_VERSION);
if (verbose)
fprintf(stderr, "Writing %s ...\n", output_path);
mtz.write_to_file(output_path);
return 0;
}
// vim:sw=2:ts=2:et:path^=../include,../third_party
<|endoftext|>
|
<commit_before>#include <node.h>
#include <nan.h>
#include <v8.h>
#include <node_buffer.h>
// dependency
#include <string.h>
#include <stdlib.h>
#include <mcrypt.h>
using namespace v8;
using namespace node;
NAN_METHOD(Rijndael) {
NanScope();
MCRYPT rijndael_module;
int err = 0;
char* error_message;
int data_size;
void* data;
char* text;
char* key;
char* iv = NULL;
int text_len;
int key_len;
bool encrypt;
char* mode;
if (args.Length() < 1 || !Buffer::HasInstance(args[0])) {
err = 1; error_message = (char*) "data must be a buffer";
} else if (args.Length() < 2 || !Buffer::HasInstance(args[1])) {
err = 1; error_message = (char*) "key must be a buffer";
} else if (args.Length() < 3 || !args[2]->IsBoolean()) {
err = 1; error_message = (char*) "encryption must be a boolean";
} else if (args.Length() < 4) {
err = 1; error_message = (char*) "block mode must be a string";
} else if (args.Length() < 5) {
err = 1; error_message = (char*) "iv must be a buffer or null";
}
if (err == 1) {
NanThrowTypeError(error_message);
NanReturnUndefined();
}
if (Buffer::HasInstance(args[4])) {
iv = Buffer::Data(args[4]);
}
String::Utf8Value modeStr(args[3]->ToString());
text = Buffer::Data(args[0]);
key = Buffer::Data(args[1]);
encrypt = args[2]->BooleanValue();
mode = *modeStr;
text_len = Buffer::Length(args[0]);
key_len = Buffer::Length(args[1]);
if (key_len != 16 && key_len != 24 && key_len != 32) {
NanThrowError("key length does not match algorithm parameters");
NanReturnUndefined();
}
rijndael_module = mcrypt_module_open((char*) "rijndael-256", NULL, mode, NULL);
if (rijndael_module == MCRYPT_FAILED) {
NanThrowError("rijndael mcrypt module failed to load");
NanReturnUndefined();
}
err = mcrypt_generic_init(rijndael_module, (void*) key, key_len, iv);
if (err < 0) {
mcrypt_module_close(rijndael_module);
NanThrowError(mcrypt_strerror(err));
NanReturnUndefined();
}
data_size = (((text_len - 1) / 32) + 1) * 32;
data = malloc(data_size);
memset(data, 0, data_size);
memcpy(data, text, text_len);
if (encrypt)
err = mcrypt_generic(rijndael_module, data, data_size);
else
err = mdecrypt_generic(rijndael_module, data, data_size);
if (err < 0) {
mcrypt_module_close(rijndael_module);
free(data);
NanThrowError(mcrypt_strerror(err));
NanReturnUndefined();
}
Local<Object> buffer = NanNewBufferHandle((char*) data, data_size);
mcrypt_module_close(rijndael_module);
free(data);
NanReturnValue(buffer);
}
void init(Handle<Object> exports) {
exports->Set(NanNew<String>("rijndael"),
NanNew<FunctionTemplate>(Rijndael)->GetFunction());
}
NODE_MODULE(rijndael, init)
<commit_msg>call "mcrypt_generic_deinit" to fix memory leaks<commit_after>#include <node.h>
#include <nan.h>
#include <v8.h>
#include <node_buffer.h>
// dependency
#include <string.h>
#include <stdlib.h>
#include <mcrypt.h>
using namespace v8;
using namespace node;
NAN_METHOD(Rijndael) {
NanScope();
MCRYPT rijndael_module;
int err = 0;
char* error_message;
int data_size;
void* data;
char* text;
char* key;
char* iv = NULL;
int text_len;
int key_len;
bool encrypt;
char* mode;
if (args.Length() < 1 || !Buffer::HasInstance(args[0])) {
err = 1; error_message = (char*) "data must be a buffer";
} else if (args.Length() < 2 || !Buffer::HasInstance(args[1])) {
err = 1; error_message = (char*) "key must be a buffer";
} else if (args.Length() < 3 || !args[2]->IsBoolean()) {
err = 1; error_message = (char*) "encryption must be a boolean";
} else if (args.Length() < 4) {
err = 1; error_message = (char*) "block mode must be a string";
} else if (args.Length() < 5) {
err = 1; error_message = (char*) "iv must be a buffer or null";
}
if (err == 1) {
NanThrowTypeError(error_message);
NanReturnUndefined();
}
if (Buffer::HasInstance(args[4])) {
iv = Buffer::Data(args[4]);
}
String::Utf8Value modeStr(args[3]->ToString());
text = Buffer::Data(args[0]);
key = Buffer::Data(args[1]);
encrypt = args[2]->BooleanValue();
mode = *modeStr;
text_len = Buffer::Length(args[0]);
key_len = Buffer::Length(args[1]);
if (key_len != 16 && key_len != 24 && key_len != 32) {
NanThrowError("key length does not match algorithm parameters");
NanReturnUndefined();
}
rijndael_module = mcrypt_module_open((char*) "rijndael-256", NULL, mode, NULL);
if (rijndael_module == MCRYPT_FAILED) {
NanThrowError("rijndael mcrypt module failed to load");
NanReturnUndefined();
}
err = mcrypt_generic_init(rijndael_module, (void*) key, key_len, iv);
if (err < 0) {
mcrypt_module_close(rijndael_module);
NanThrowError(mcrypt_strerror(err));
NanReturnUndefined();
}
data_size = (((text_len - 1) / 32) + 1) * 32;
data = malloc(data_size);
memset(data, 0, data_size);
memcpy(data, text, text_len);
if (encrypt)
err = mcrypt_generic(rijndael_module, data, data_size);
else
err = mdecrypt_generic(rijndael_module, data, data_size);
if (err < 0) {
mcrypt_module_close(rijndael_module);
free(data);
NanThrowError(mcrypt_strerror(err));
NanReturnUndefined();
}
err = mcrypt_generic_deinit(rijndael_module);
if (err < 0) {
mcrypt_module_close(rijndael_module);
free(data);
NanThrowError(mcrypt_strerror(err));
NanReturnUndefined();
}
Local<Object> buffer = NanNewBufferHandle((char*) data, data_size);
mcrypt_module_close(rijndael_module);
free(data);
NanReturnValue(buffer);
}
void init(Handle<Object> exports) {
exports->Set(NanNew<String>("rijndael"),
NanNew<FunctionTemplate>(Rijndael)->GetFunction());
}
NODE_MODULE(rijndael, init)
<|endoftext|>
|
<commit_before>#ifndef VEXCL_VEXCL_HPP
#define VEXCL_VEXCL_HPP
/*
The MIT License
Copyright (c) 2012 Denis Demidov <ddemidov@ksu.ru>
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.
*/
/**
* \file vexcl.hpp
* \author Denis Demidov <ddemidov@ksu.ru>
* \brief Vector expression template library for OpenCL.
*/
/**
\mainpage VexCL
VexCL is vector expression template library for OpenCL. It has been created for
ease of C++ based OpenCL development. Multi-device (and multi-platform)
computations are supported. The source code is available at
https://github.com/ddemidov/vexcl.
\section devlist Selection of compute devices
You can select any number of available compute devices, which satisfy provided
filters. Filter is a functor returning bool and acting on a cl::Device
parameter. Several standard filters are provided, such as device type or name
filter, double precision support etc. Filters can be combined with logical
operators. In the example below all devices with names matching "Radeon" and
supporting double precision are selected:
\code
#include <vexcl/vexcl.hpp>
using namespace vex;
int main() {
vex::Context ctx(Filter::Name("Radeon") && Filter::DoublePrecision);
std::cout << ctx << std::endl;
}
\endcode
vex::Context object holds list of initialized OpenCL contexts and command
queues for each filtered device. If you just need list of available devices
without creating contexts and queues on them, then look for device_list()
function in documenation.
\section vector Memory allocation and vector arithmetic
Once you got queue list, you can allocate OpenCL buffers on the associated
devices. vex::vector constructor accepts std::vector of cl::CommandQueue. The
contents of the created vector will be partitioned between each queue
(presumably, each of the provided queues is linked with separate device). Size
of each partition will be proportional to relative device bandwidth unless
macro VEXCL_DUMB_PARTITIONING is defined, in which case equal partitioning
scheme will be applied. Device bandwidth is measured first time it is requested
by launch of small test kernel.
Multi-platform computation is supported (that is, you can spread your vectors
across devices by different vendors), but should be used with caution: all
computations will be performed with the speed of the slowest device selected.
In the example below host vector is allocated and initialized, then copied to
all GPU devices found in the system. A couple of empty device vectors are
allocated as well:
\code
const size_t n = 1 << 20;
std::vector<double> x(n);
std::generate(x.begin(), x.end(), [](){ return (double)rand() / RAND_MAX; });
vex::Context ctx(Filter::Type(CL_DEVICE_TYPE_GPU));
vex::vector<double> X(ctx.queue(), x);
vex::vector<double> Y(ctx.queue(), n);
vex::vector<double> Z(ctx.queue(), n);
\endcode
You can now use simple vector arithmetic with device vector. For every
expression you use, appropriate kernel is compiled (first time it is
encountered in your program) and called automagically. If you want to see
sources of the generated kernels on the standard output, define
VEXCL_SHOW_KERNELS macro before including VexCL headers.
Vectors are processed in parallel across all devices they were allocated on:
\code
Y = 42;
Z = sqrt(2 * X) + cos(Y);
\endcode
You can copy the result back to host or you can use vector::operator[] to
read (or write) vector elements directly. Though latter technique is very
ineffective and should be used for debugging purposes only.
\code
copy(Z, x);
assert(x[42] == Z[42]);
\endcode
Another frequently performed operation is reduction of a vector expression to
single value, such as summation. This can be done with vex::Reductor class:
\code
Reductor<double> sum(ctx.queue());
std::cout << sum(Z) << std::endl;
std::cout << sum(sqrt(2 * X) + cos(Y)) << std::endl;
\endcode
\section stencil Stencil convolution
Stencil convolution operation comes in handy in many situations. For example,
it allows us to apply a moving average filter to a device vector. All you need
is to construct a vex::stencil object:
\code
// Moving average with 5-points window.
std::vector<double> sdata(5, 0.2);
stencil(ctx.queue(), sdata, sdata.size() / 2);
vex::vector<double> x(ctx.queue(), 1024 * 1024);
vex::vector<double> y(ctx.queue(), 1024 * 1024);
x = 1;
y = x * s; // convolve x with s
\endcode
\section spmv Sparse matrix-vector multiplication
One of the most common operations in linear algebra is matrix-vector
multiplication. Class vex::SpMat holds representation of a sparse matrix,
spanning several devices. In the example below it is used for solution of a
system of linear equations with conjugate gradients method:
\code
typedef double real;
// Solve system of linear equations A u = f with conjugate gradients method.
// Input matrix is represented in CSR format (parameters row, col, and val).
void cg_gpu(
const std::vector<size_t> &row, // Indices to col and val vectors.
const std::vector<size_t> &col, // Column numbers of non-zero elements.
const std::vector<real> &val, // Values of non-zero elements.
const std::vector<real> &rhs, // Right-hand side.
std::vector<real> &x // In: initial approximation; out: result.
)
{
// Init OpenCL.
vex::Context ctx(Filter::Type(CL_DEVICE_TYPE_GPU));
// Move data to compute devices.
size_t n = x.size();
vex::SpMat<real> A(ctx.queue(), n, row.data(), col.data(), val.data());
vex::vector<real> f(ctx.queue(), rhs);
vex::vector<real> u(ctx.queue(), x);
vex::vector<real> r(ctx.queue(), n);
vex::vector<real> p(ctx.queue(), n);
vex::vector<real> q(ctx.queue(), n);
Reductor<real,MAX> max(ctx.queue());
Reductor<real,SUM> sum(ctx.queue());
// Solve equation Au = f with conjugate gradients method.
real rho1, rho2;
r = f - A * u;
for(uint iter = 0; max(fabs(r)) > 1e-8 && iter < n; iter++) {
rho1 = sum(r * r);
if (iter == 0) {
p = r;
} else {
real beta = rho1 / rho2;
p = r + beta * p;
}
q = A * p;
real alpha = rho1 / sum(p * q);
u += alpha * p;
r -= alpha * q;
rho2 = rho1;
}
// Get result to host.
copy(u, x);
}
\endcode
\section userfun User-defined functions
Simple arithmetic expressions are sometimes not enough. Imagine that you need
to count how many elements in vector x are greater that their counterparts in
vector y. This may be achieved by introduction of custom function. In order
to build such a function, you need to supply its body, its return type and
types of its arguments. After that, you can apply the function to any valid
vector expressions:
\code
// Function body has to be defined at global scope, and it has to be of `extern
// const char[]` type. This allows us to use it as a template parameter.
extern const char one_greater_than_other[] = "return prm1 > prm2 ? 1 : 0;";
UserFunction<one_greater_than_other, size_t(float, float)> greater;
size_t count_if_greater(
const Reductor<size_t, SUM> &sum,
const vex::vector<float> &x,
const vex::vector<float> &y
)
{
return sum(greater(x, y));
}
\endcode
You could also write sum(greater(x + y, 5 * y)), or use any other expressions
as parameters to the greater() call. Note that in the function body
parameters are always named as prm1, prm2, etc.
\section multivector Multi-component vectors
Class template vex::multivector<T,N> allows to store several equally sized
device vectors and perform computations on all components synchronously.
Operations are delegated to the underlying vectors. Expressions may include
std::array<T,N> values, where N is equal to the number of multivector
components. Each component gets corresponding element of std::array<> when
expression is applied.
\code
const size_t n = 1 << 20;
std::vector<double> host(n * 3);
std::generate(host.begin(), host.end(), rand);
vex::multivector<double,3> x(ctx.queue(), host);
vex::multivector<double,3> y(ctx.queue(), n);
std::array<int, 3> c = {4, 5, 6};
y = 2 * cos(x) - c;
std::array<double,3> v = y[42];
assert(fabs(v[1] - (2 * cos(host[n + 42]) - c[1])) < 1e-8);
\endcode
Components of a multivector may be accessed with operator():
\code
vex::vector<double> z = y(1);
\endcode
\section custkern Using custom kernels
Custom kernels are of course possible as well. vector::operator(uint)
returns cl::Buffer object for a specified device:
\code
vex::Context ctx(Filter::Type(CL_DEVICE_TYPE_GPU));
const size_t n = 1 << 20;
vex::vector<float> x(ctx.queue(), n);
auto program = build_sources(context, std::string(
"kernel void dummy(ulong size, global float *x)\n"
"{\n"
" size_t i = get_global_id(0);\n"
" if (i < size) x[i] = 4.2;\n"
"}\n"
));
for(uint d = 0; d < ctx.size(); d++) {
auto dummy = cl::Kernel(program, "dummy").bind(ctx.queue()[d], alignup(n, 256), 256);
dummy((cl_ulong)x.part_size(d), x(d));
}
Reductor<float,SUM> sum(ctx.queue());
std::cout << sum(x) << std::endl;
\endcode
\section scalability Scalability
In the images below, scalability of the library with respect to number of
compute devices is shown. Effective performance (GFLOPS) and bandwidth (GB/sec)
were measured by launching big number of test kernels on one, two, or three
Nvidia Tesla C2070 cards. The results shown are averaged over 20 runs.
The details of the experiments may be found in <a
href="https://github.com/ddemidov/vexcl/blob/master/examples/benchmark.cpp">
examples/benchmark.cpp</a> file. Basically, performance of the following code
was measured:
\code
// Vector arithmetic
a += b + c * d;
// Reduction
double s = sum(a * b);
// SpMV
y += A * x;
\endcode
\image html perf.png ""
\section compilers Supported compilers
VexCL makes heavy use of C++11 features, so your compiler has to be modern
enough. GCC version 4.6 and above is fully supported. Microsoft Visual C++ 2010
manages to compile the project with some features disabled: since it does not
support variadic templates, only one-argument builtin functions are enabled;
user functions are not available at all.
*/
#ifdef WIN32
# pragma warning(push)
# pragma warning(disable : 4290)
# define NOMINMAX
#endif
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <iostream>
#include <vexcl/util.hpp>
#include <vexcl/devlist.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/reduce.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/stencil.hpp>
#include <vexcl/profiler.hpp>
#ifdef WIN32
# pragma warning(pop)
#endif
#endif
<commit_msg>touched documentation<commit_after>#ifndef VEXCL_VEXCL_HPP
#define VEXCL_VEXCL_HPP
/*
The MIT License
Copyright (c) 2012 Denis Demidov <ddemidov@ksu.ru>
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.
*/
/**
* \file vexcl.hpp
* \author Denis Demidov <ddemidov@ksu.ru>
* \brief Vector expression template library for OpenCL.
*/
/**
\mainpage VexCL
VexCL is vector expression template library for OpenCL. It has been created for
ease of C++ based OpenCL development. Multi-device (and multi-platform)
computations are supported. The source code is available at
https://github.com/ddemidov/vexcl.
\section devlist Selection of compute devices
You can select any number of available compute devices, which satisfy provided
filters. Filter is a functor returning bool and acting on a cl::Device
parameter. Several standard filters are provided, such as device type or name
filter, double precision support etc. Filters can be combined with logical
operators. In the example below all devices with names matching "Radeon" and
supporting double precision are selected:
\code
#include <vexcl/vexcl.hpp>
using namespace vex;
int main() {
vex::Context ctx(Filter::Name("Radeon") && Filter::DoublePrecision);
std::cout << ctx << std::endl;
}
\endcode
vex::Context object holds list of initialized OpenCL contexts and command
queues for each filtered device. If you just need list of available devices
without creating contexts and queues on them, then look for device_list()
function in documenation.
\section vector Memory allocation and vector arithmetic
Once you got queue list, you can allocate OpenCL buffers on the associated
devices. vex::vector constructor accepts std::vector of cl::CommandQueue. The
contents of the created vector will be partitioned between each queue
(presumably, each of the provided queues is linked with separate device). Size
of each partition will be proportional to relative device bandwidth unless
macro VEXCL_DUMB_PARTITIONING is defined, in which case equal partitioning
scheme will be applied. Device bandwidth is measured first time it is requested
by launch of small test kernel.
Multi-platform computation is supported (that is, you can spread your vectors
across devices by different vendors), but should be used with caution: all
computations will be performed with the speed of the slowest device selected.
In the example below host vector is allocated and initialized, then copied to
all GPU devices found in the system. A couple of empty device vectors are
allocated as well:
\code
const size_t n = 1 << 20;
std::vector<double> x(n);
std::generate(x.begin(), x.end(), [](){ return (double)rand() / RAND_MAX; });
vex::Context ctx(Filter::Type(CL_DEVICE_TYPE_GPU));
vex::vector<double> X(ctx.queue(), x);
vex::vector<double> Y(ctx.queue(), n);
vex::vector<double> Z(ctx.queue(), n);
\endcode
You can now use simple vector arithmetic with device vector. For every
expression you use, appropriate kernel is compiled (first time it is
encountered in your program) and called automagically. If you want to see
sources of the generated kernels on the standard output, define
VEXCL_SHOW_KERNELS macro before including VexCL headers.
Vectors are processed in parallel across all devices they were allocated on:
\code
Y = 42;
Z = sqrt(2 * X) + cos(Y);
\endcode
You can copy the result back to host or you can use vector::operator[] to
read (or write) vector elements directly. Though latter technique is very
ineffective and should be used for debugging purposes only.
\code
copy(Z, x);
assert(x[42] == Z[42]);
\endcode
Another frequently performed operation is reduction of a vector expression to
single value, such as summation. This can be done with vex::Reductor class:
\code
Reductor<double> sum(ctx.queue());
std::cout << sum(Z) << std::endl;
std::cout << sum(sqrt(2 * X) + cos(Y)) << std::endl;
\endcode
\section stencil Stencil convolution
Stencil convolution operation comes in handy in many situations. For example,
it allows us to apply a moving average filter to a device vector. All you need
is to construct a vex::stencil object:
\code
// Moving average with 5-points window.
std::vector<double> sdata(5, 0.2);
stencil(ctx.queue(), sdata, sdata.size() / 2);
vex::vector<double> x(ctx.queue(), 1024 * 1024);
vex::vector<double> y(ctx.queue(), 1024 * 1024);
x = 1;
y = x * s; // convolve x with s
\endcode
\section spmv Sparse matrix-vector multiplication
One of the most common operations in linear algebra is matrix-vector
multiplication. Class vex::SpMat holds representation of a sparse matrix,
spanning several devices. In the example below it is used for solution of a
system of linear equations with conjugate gradients method:
\code
typedef double real;
// Solve system of linear equations A u = f with conjugate gradients method.
// Input matrix is represented in CSR format (parameters row, col, and val).
void cg_gpu(
const std::vector<size_t> &row, // Indices to col and val vectors.
const std::vector<size_t> &col, // Column numbers of non-zero elements.
const std::vector<real> &val, // Values of non-zero elements.
const std::vector<real> &rhs, // Right-hand side.
std::vector<real> &x // In: initial approximation; out: result.
)
{
// Init OpenCL.
vex::Context ctx(Filter::Type(CL_DEVICE_TYPE_GPU));
// Move data to compute devices.
size_t n = x.size();
vex::SpMat<real> A(ctx.queue(), n, row.data(), col.data(), val.data());
vex::vector<real> f(ctx.queue(), rhs);
vex::vector<real> u(ctx.queue(), x);
vex::vector<real> r(ctx.queue(), n);
vex::vector<real> p(ctx.queue(), n);
vex::vector<real> q(ctx.queue(), n);
Reductor<real,MAX> max(ctx.queue());
Reductor<real,SUM> sum(ctx.queue());
// Solve equation Au = f with conjugate gradients method.
real rho1, rho2;
r = f - A * u;
for(uint iter = 0; max(fabs(r)) > 1e-8 && iter < n; iter++) {
rho1 = sum(r * r);
if (iter == 0) {
p = r;
} else {
real beta = rho1 / rho2;
p = r + beta * p;
}
q = A * p;
real alpha = rho1 / sum(p * q);
u += alpha * p;
r -= alpha * q;
rho2 = rho1;
}
// Get result to host.
copy(u, x);
}
\endcode
\section userfun User-defined functions
Simple arithmetic expressions are sometimes not enough. Imagine that you need
to count how many elements in vector x are greater that their counterparts in
vector y. This may be achieved by introduction of custom function. In order
to build such a function, you need to supply its body, its return type and
types of its arguments. After that, you can apply the function to any valid
vector expressions:
\code
// Function body has to be defined at global scope, and it has to be of `extern
// const char[]` type. This allows us to use it as a template parameter.
extern const char greater_body[] = "return prm1 > prm2 ? 1 : 0;";
UserFunction<greater_body, size_t(float, float)> greater;
size_t count_if_greater(
const Reductor<size_t, SUM> &sum,
const vex::vector<float> &x,
const vex::vector<float> &y
)
{
return sum(greater(x, y));
}
\endcode
You could also write sum(greater(x + y, 5 * y)), or use any other expressions
as parameters to the greater() call. Note that in the function body
parameters are always named as prm1, prm2, etc.
\section multivector Multi-component vectors
Class template vex::multivector<T,N> allows to store several equally sized
device vectors and perform computations on all components synchronously.
Operations are delegated to the underlying vectors. Expressions may include
std::array<T,N> values, where N is equal to the number of multivector
components. Each component gets corresponding element of std::array<> when
expression is applied.
\code
const size_t n = 1 << 20;
std::vector<double> host(n * 3);
std::generate(host.begin(), host.end(), rand);
vex::multivector<double,3> x(ctx.queue(), host);
vex::multivector<double,3> y(ctx.queue(), n);
std::array<int, 3> c = {4, 5, 6};
y = 2 * cos(x) - c;
std::array<double,3> v = y[42];
assert(fabs(v[1] - (2 * cos(host[n + 42]) - c[1])) < 1e-8);
\endcode
Components of a multivector may be accessed with operator():
\code
vex::vector<double> z = y(1);
\endcode
\section custkern Using custom kernels
Custom kernels are of course possible as well. vector::operator(uint)
returns cl::Buffer object for a specified device:
\code
vex::Context ctx(Filter::Type(CL_DEVICE_TYPE_GPU));
const size_t n = 1 << 20;
vex::vector<float> x(ctx.queue(), n);
auto program = build_sources(context, std::string(
"kernel void dummy(ulong size, global float *x)\n"
"{\n"
" size_t i = get_global_id(0);\n"
" if (i < size) x[i] = 4.2;\n"
"}\n"
));
for(uint d = 0; d < ctx.size(); d++) {
auto dummy = cl::Kernel(program, "dummy").bind(ctx.queue()[d], alignup(n, 256), 256);
dummy((cl_ulong)x.part_size(d), x(d));
}
Reductor<float,SUM> sum(ctx.queue());
std::cout << sum(x) << std::endl;
\endcode
\section scalability Scalability
In the images below, scalability of the library with respect to number of
compute devices is shown. Effective performance (GFLOPS) and bandwidth (GB/sec)
were measured by launching big number of test kernels on one, two, or three
Nvidia Tesla C2070 cards. The results shown are averaged over 20 runs.
The details of the experiments may be found in <a
href="https://github.com/ddemidov/vexcl/blob/master/examples/benchmark.cpp">
examples/benchmark.cpp</a> file. Basically, performance of the following code
was measured:
\code
// Vector arithmetic
a += b + c * d;
// Reduction
double s = sum(a * b);
// SpMV
y += A * x;
\endcode
\image html perf.png ""
\section compilers Supported compilers
VexCL makes heavy use of C++11 features, so your compiler has to be modern
enough. GCC version 4.6 and above is fully supported. Microsoft Visual C++ 2010
manages to compile the project with some features disabled: since it does not
support variadic templates, only one-argument builtin functions are enabled;
user functions are not available at all.
*/
#ifdef WIN32
# pragma warning(push)
# pragma warning(disable : 4290)
# define NOMINMAX
#endif
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <iostream>
#include <vexcl/util.hpp>
#include <vexcl/devlist.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/reduce.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/stencil.hpp>
#include <vexcl/profiler.hpp>
#ifdef WIN32
# pragma warning(pop)
#endif
#endif
<|endoftext|>
|
<commit_before>#include <math.h>
#include <robot_p/robothw.h>
#include <boost/math/constants/constants.hpp>
using namespace robotp;
RobotHW::RobotHW(ros::NodeHandle &nh_private)
: jnt_state_interface()
, jnt_vel_interface()
, serial_()
, ticks_per_revolution_(258)
, input_buff_()
, alarm_(false)
{
// connect and register the joint state interface
hardware_interface::JointStateHandle state_handle_left(
"front_left_wheel", &pos_[LEFT], &vel_[LEFT], &eff_[LEFT]);
jnt_state_interface.registerHandle(state_handle_left);
hardware_interface::JointStateHandle state_handle_right(
"front_right_wheel", &pos_[RIGHT], &vel_[RIGHT], &eff_[RIGHT]);
jnt_state_interface.registerHandle(state_handle_right);
registerInterface(&jnt_state_interface);
// connect and register the joint position interface
hardware_interface::JointHandle vel_handle_left(
jnt_state_interface.getHandle("front_left_wheel"), &cmd_[LEFT]);
jnt_vel_interface.registerHandle(vel_handle_left);
hardware_interface::JointHandle vel_handle_right(
jnt_state_interface.getHandle("front_right_wheel"), &cmd_[RIGHT]);
jnt_vel_interface.registerHandle(vel_handle_right);
registerInterface(&jnt_vel_interface);
// initialize parameters
std::string port;
float Kp, Ki, Kd;
nh_private.param<double>("ticks_per_revolution", ticks_per_revolution_, 258);
nh_private.param<std::string>("serial_port", port, "/dev/ttyS0");
nh_private.param<float>("Kp", Kp, 1);
nh_private.param<float>("Ki", Kd, 0.3);
nh_private.param<float>("Kd", Ki, 0.5);
serial_.setPort(port);
serial_.setBaudrate(57600);
try {
serial_.open();
} catch (serial::SerialException e) {
ROS_ERROR_STREAM("[ROBOTHW]: Serial exception: " << e.what());
return;
} catch (serial::IOException e) {
ROS_ERROR_STREAM("ROBOT_P_CONTROL: Serial IO exception: " << e.what());
return;
}
sendMsg(createStartMsg());
sendMsg(createPIDMsg('P', Kp));
sendMsg(createPIDMsg('I', Ki));
sendMsg(createPIDMsg('D', Kd));
}
robotp::RobotHW::~RobotHW()
{
sendMsg(createStopMsg());
}
void RobotHW::read(const ros::Time &time, const ros::Duration &period)
{
const size_t MESSAGE_SIZE = 6;
size_t message_count = serial_.available() / MESSAGE_SIZE;
std::array<double, 2> ticks = {0, 0};
for (size_t i = 0; i < message_count; ++i) {
if (serial_.read(input_buff_.data(), MESSAGE_SIZE) != MESSAGE_SIZE) {
ROS_ERROR_STREAM("ROBOT_P_CONTROL:unable to read "
<< MESSAGE_SIZE << " byte message from serial "
"input");
return;
}
Msg32 *msg = reinterpret_cast<Msg32 *>(input_buff_.data());
switch (msg->id) {
case 'T':
// ticks per second
ticks[0] += static_cast<double>(msg->left) * TICKS_TIME_MULTIPLIER;
ticks[1] += static_cast<double>(msg->right) * TICKS_TIME_MULTIPLIER;
ROS_INFO_STREAM("msg: " << msg->left << " " << msg->right);
break;
case 'A':
ROS_WARN_STREAM("ROBOT_P_CONTROL: Alarm received in " << time);
alarm_ = true;
break;
default:
ROS_ERROR_STREAM(
"ROBOT_P_CONTROL: Unknown input message type: " << msg->id);
break;
}
}
// ticks/s to rad/s
double conversion = 2 * M_PI / ticks_per_revolution_;
for (size_t i = 0; i < 2; ++i) {
vel_[i] = ticks[i] * conversion; // rad/s
pos_[i] += vel_[i] * period.toSec();
eff_[i] = 0;
}
ROS_INFO_STREAM("ROBOT_P_CONTROL: read -> speed [rad/s] L:"
<< vel_[0] << " R: " << vel_[1]);
ROS_INFO_STREAM("ROBOT_P_CONTROL: read -> position [rad] L:"
<< pos_[0] << " R: " << pos_[1]);
}
void RobotHW::write()
{
if (alarm_) {
sendMsg(createStartMsg());
alarm_ = false;
} else {
sendMsg(createVelocityMsg(cmd_[0], cmd_[1]));
}
}
robotp::RobotHW::Msg32 robotp::RobotHW::createPIDMsg(char letter,
float data) const
{
Msg32 msg;
msg.id = letter;
msg.pid_param = static_cast<uint16_t>(std::trunc(data * FLOAT_MULTIPLIER));
msg.padding = 0;
msg.crc = 0;
return msg;
}
robotp::RobotHW::Msg32
robotp::RobotHW::createVelocityMsg(double left_vel, double right_vel) const
{
Msg32 msg;
msg.id = 'V';
msg.crc = 0;
// rad/s to ticks/s
double conversion = ticks_per_revolution_ / 2 * M_PI;
auto calcVelocity = [this, conversion](double vel) -> int16_t {
return static_cast<int16_t>(std::round(vel * conversion)) /
TICKS_TIME_MULTIPLIER;
};
msg.left = calcVelocity(left_vel);
msg.right = calcVelocity(right_vel);
return msg;
}
robotp::RobotHW::Msg32 robotp::RobotHW::createStartMsg() const
{
Msg32 msg;
msg.id = 'S';
return msg;
}
robotp::RobotHW::Msg32 robotp::RobotHW::createStopMsg() const
{
Msg32 msg;
msg.id = 'E';
return msg;
}
<commit_msg>Setting up no handshake<commit_after>#include <math.h>
#include <robot_p/robothw.h>
#include <boost/math/constants/constants.hpp>
using namespace robotp;
RobotHW::RobotHW(ros::NodeHandle &nh_private)
: jnt_state_interface()
, jnt_vel_interface()
, serial_()
, ticks_per_revolution_(258)
, input_buff_()
, alarm_(false)
{
// connect and register the joint state interface
hardware_interface::JointStateHandle state_handle_left(
"front_left_wheel", &pos_[LEFT], &vel_[LEFT], &eff_[LEFT]);
jnt_state_interface.registerHandle(state_handle_left);
hardware_interface::JointStateHandle state_handle_right(
"front_right_wheel", &pos_[RIGHT], &vel_[RIGHT], &eff_[RIGHT]);
jnt_state_interface.registerHandle(state_handle_right);
registerInterface(&jnt_state_interface);
// connect and register the joint position interface
hardware_interface::JointHandle vel_handle_left(
jnt_state_interface.getHandle("front_left_wheel"), &cmd_[LEFT]);
jnt_vel_interface.registerHandle(vel_handle_left);
hardware_interface::JointHandle vel_handle_right(
jnt_state_interface.getHandle("front_right_wheel"), &cmd_[RIGHT]);
jnt_vel_interface.registerHandle(vel_handle_right);
registerInterface(&jnt_vel_interface);
// initialize parameters
std::string port;
float Kp, Ki, Kd;
nh_private.param<double>("ticks_per_revolution", ticks_per_revolution_, 258);
nh_private.param<std::string>("serial_port", port, "/dev/ttyS0");
nh_private.param<float>("Kp", Kp, 1);
nh_private.param<float>("Ki", Kd, 0.3);
nh_private.param<float>("Kd", Ki, 0.5);
serial_.setPort(port);
serial_.setRTS(false);
serial_.setDTR(false);
serial_.setBaudrate(57600);
try {
serial_.open();
} catch (serial::SerialException e) {
ROS_ERROR_STREAM("[ROBOTHW]: Serial exception: " << e.what());
return;
} catch (serial::IOException e) {
ROS_ERROR_STREAM("ROBOT_P_CONTROL: Serial IO exception: " << e.what());
return;
}
sendMsg(createStartMsg());
sendMsg(createPIDMsg('P', Kp));
sendMsg(createPIDMsg('I', Ki));
sendMsg(createPIDMsg('D', Kd));
}
robotp::RobotHW::~RobotHW()
{
sendMsg(createStopMsg());
}
void RobotHW::read(const ros::Time &time, const ros::Duration &period)
{
const size_t MESSAGE_SIZE = 6;
size_t message_count = serial_.available() / MESSAGE_SIZE;
std::array<double, 2> ticks = {0, 0};
for (size_t i = 0; i < message_count; ++i) {
if (serial_.read(input_buff_.data(), MESSAGE_SIZE) != MESSAGE_SIZE) {
ROS_ERROR_STREAM("ROBOT_P_CONTROL:unable to read "
<< MESSAGE_SIZE << " byte message from serial "
"input");
return;
}
Msg32 *msg = reinterpret_cast<Msg32 *>(input_buff_.data());
switch (msg->id) {
case 'T':
// ticks per second
ticks[0] += static_cast<double>(msg->left) * TICKS_TIME_MULTIPLIER;
ticks[1] += static_cast<double>(msg->right) * TICKS_TIME_MULTIPLIER;
ROS_INFO_STREAM("msg: " << msg->left << " " << msg->right);
break;
case 'A':
ROS_WARN_STREAM("ROBOT_P_CONTROL: Alarm received in " << time);
alarm_ = true;
break;
default:
ROS_ERROR_STREAM(
"ROBOT_P_CONTROL: Unknown input message type: " << msg->id);
break;
}
}
// ticks/s to rad/s
double conversion = 2 * M_PI / ticks_per_revolution_;
for (size_t i = 0; i < 2; ++i) {
vel_[i] = ticks[i] * conversion; // rad/s
pos_[i] += vel_[i] * period.toSec();
eff_[i] = 0;
}
ROS_INFO_STREAM("ROBOT_P_CONTROL: read -> speed [rad/s] L:"
<< vel_[0] << " R: " << vel_[1]);
ROS_INFO_STREAM("ROBOT_P_CONTROL: read -> position [rad] L:"
<< pos_[0] << " R: " << pos_[1]);
}
void RobotHW::write()
{
if (alarm_) {
sendMsg(createStartMsg());
alarm_ = false;
} else {
sendMsg(createVelocityMsg(cmd_[0], cmd_[1]));
}
}
robotp::RobotHW::Msg32 robotp::RobotHW::createPIDMsg(char letter,
float data) const
{
Msg32 msg;
msg.id = letter;
msg.pid_param = static_cast<uint16_t>(std::trunc(data * FLOAT_MULTIPLIER));
msg.padding = 0;
msg.crc = 0;
return msg;
}
robotp::RobotHW::Msg32
robotp::RobotHW::createVelocityMsg(double left_vel, double right_vel) const
{
Msg32 msg;
msg.id = 'V';
msg.crc = 0;
// rad/s to ticks/s
double conversion = ticks_per_revolution_ / 2 * M_PI;
auto calcVelocity = [this, conversion](double vel) -> int16_t {
return static_cast<int16_t>(std::round(vel * conversion)) /
TICKS_TIME_MULTIPLIER;
};
msg.left = calcVelocity(left_vel);
msg.right = calcVelocity(right_vel);
return msg;
}
robotp::RobotHW::Msg32 robotp::RobotHW::createStartMsg() const
{
Msg32 msg;
msg.id = 'S';
return msg;
}
robotp::RobotHW::Msg32 robotp::RobotHW::createStopMsg() const
{
Msg32 msg;
msg.id = 'E';
return msg;
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativedeviceinfo_p.h"
#include "qsystemdeviceinfo.h"
#include <QMetaType>
#include <QDebug>
QT_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(QSystemDeviceInfo, deviceInfo)
/*!
\qmlclass DeviceInfo QDeclarativeDeviceInfo
\brief The DeviceInfo element allows you to access information anbout the device and
receive notifications from the device.
\inherits QSystemDeviceInfo
\ingroup qml-systeminfo
This element is part of the \bold{QtMobility.systeminfo 1.1} module.
It is a convience class to make QML usage easier.
Note: To use notification signals, you need to set the monitor* properties to true.
\sa QSystemDeviceInfo
*/
/*!
\qmlsignal DeviceInfo::batteryLevelChanged(int)
This handler is called when battery level has changed.
*/
/*!
\qmlsignal DeviceInfo::batteryStatusChanged(DeviceInfo::BatteryStatus)
This handler is called when battery status has changed.
*/
/*!
\qmlsignal DeviceInfo::powerStateChanged(DeviceINfo::PowerState)
This handler is called when the power state has changed.
*/
/*!
\qmlsignal DeviceInfo::currentProfileChanged(DeviceInfo::Profile)
This handler is called when current device profile has changed.
*/
/*!
\qmlsignal DeviceInfo::bluetoothStateChanged(bool)
This handler is called when bluetooth power state has changed.
*/
/*!
\qmlsignal DeviceInfo::wirelessKeyboardConnected(bool)
This signal is emitted whenever a wireless keyboard is connected
*/
/*!
\qmlsignal DeviceInfo::keyboardFlipped(bool)
This signal is emitted whenever a phone flips open.
*/
/*!
\qmlsignal DeviceInfo::deviceLocked(bool)
This signal is emitted whenever the device lock state changes
*/
/*!
\qmlsignal DeviceInfo::lockStatusChanged(DeviceInfo::LockTypeFlags)
This signal is emitted whenever the lock state changes
*/
/*!
\qmlsignal DeviceInfo::thermalStateChanged(DeviceInfo::ThermalState)
This handler is called when thermal state has changed.
*/
QDeclarativeDeviceInfo::QDeclarativeDeviceInfo(QObject *parent) :
QSystemDeviceInfo(parent)
{
}
/*!
This function starts the batteryLevelChanged notification
*/
void QDeclarativeDeviceInfo::startBatteryLevelChanged(bool on)
{
monitoringBatteryLevel = on;
if(on) {
connect(deviceInfo(),SIGNAL(batteryLevelChanged(int)),
this,SIGNAL(batteryLevelChanged(int)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(batteryLevelChanged(int)),
this,SIGNAL(batteryLevelChanged(int)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorBatteryLevelChanges
Use the monitorBatteryLevelChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorBatteryLevelChanges()
{
return monitoringBatteryLevel;
}
/*!
This function starts the batteryStatusChanged notification
*/
void QDeclarativeDeviceInfo::startBatteryStatusChanged(bool on)
{
monitoringBatteryStatus = on;
if(on) {
connect(deviceInfo(),SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorBatteryStatusChanges
Use the monitorBatteryStatusChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorBatteryStatusChanges()
{
return monitoringBatteryStatus;
}
/*!
This function starts the powerStateChanged notification
*/
void QDeclarativeDeviceInfo::startPowerStateChanged(bool on)
{
monitoringPowerState = on;
if(on) {
connect(deviceInfo(),SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorPowerStateChanges
Use the monitorPowerStateChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorPowerStateChanges()
{
return monitoringPowerState;
}
/*!
This function is needed to start currentProfileChanged notification
*/
void QDeclarativeDeviceInfo::startCurrentProfileChanged(bool on)
{
monitoringCurrentProfile = on;
if(on) {
connect(deviceInfo(),SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorCurrentProfileChanges
Use the monitorCurrentProfileChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorCurrentProfileChanges()
{
return monitoringCurrentProfile;
}
/*!
This function starts the bluetoothStateChanged notification
*/
void QDeclarativeDeviceInfo::startBluetoothStateChanged(bool on)
{
monitorBluetoothState = on;
if(on) {
connect(deviceInfo(),SIGNAL(bluetoothStateChanged(bool)),
this,SIGNAL(bluetoothStateChanged(bool)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(bluetoothStateChanged(bool)),
this,SIGNAL(bluetoothStateChanged(bool)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorBluetoothStateChanges
Use the bluetoothStateChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorBluetoothStateChanges()
{
return monitorBluetoothState;
}
/*!
This function starts the thermalStateChanged notification
*/
void QDeclarativeDeviceInfo::startThermalStateChanged(bool on)
{
monitorThermalState = on;
if (on) {
connect(deviceInfo(), SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)),
this, SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)), Qt::UniqueConnection);
} else {
disconnect(deviceInfo(), SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)),
this, SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorThermalStateChanges
Use the thermalStateChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorThermalStateChanges()
{
return monitorThermalState;
}
/*!
\qmlproperty bool DeviceInfo::monitorWirelessKeyboardConnects()
Start the connection for the wirelessKeyboardConnected signal.
*/
bool QDeclarativeDeviceInfo::monitorWirelessKeyboardConnects()
{
return monitoringWirelessKeyboard;
}
/*!
This function starts the startBatteryStatusChanged notification.
*/
void QDeclarativeDeviceInfo::startWirelessKeyboardConnected(bool on)
{
monitoringWirelessKeyboard = on;
if(on) {
connect(deviceInfo(),SIGNAL(wirelessKeyboardConnected(bool)),
this,SIGNAL(wirelessKeyboardConnected(bool)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(wirelessKeyboardConnected(bool)),
this,SIGNAL(wirelessKeyboardConnected(bool)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorKeyboardFlips()
Start the connection for the keyboardFlipped signal.
*/
bool QDeclarativeDeviceInfo::monitorKeyboardFlips()
{
return monitoringKeyboardFlipped;
}
/*!
This function starts the startKeyboardFlipped notification.
*/
void QDeclarativeDeviceInfo::startKeyboardFlipped(bool on)
{
monitoringKeyboardFlipped = on;
if(on) {
connect(deviceInfo(),SIGNAL(keyboardFlipped(bool)),
this,SIGNAL(keyboardFlipped(bool)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(keyboardFlipped(bool)),
this,SIGNAL(keyboardFlipped(bool)));
}
}
/*!
\qmlproperty bool Device::monitorDeviceLocks()
Start the connection for the deviceLocked signal.
*/
bool QDeclarativeDeviceInfo::monitorDeviceLocks()
{
return monitoringDeviceLocked;
}
/*!
This function starts the startDeviceLocked notification.
*/
void QDeclarativeDeviceInfo::startDeviceLocked(bool on)
{
monitoringDeviceLocked = on;
if(on) {
connect(deviceInfo(),SIGNAL(deviceLocked(bool)),
this,SIGNAL(deviceLocked(bool)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(deviceLocked(bool)),
this,SIGNAL(deviceLocked(bool)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorLockStatusChanges()
Start the connection for the lockStatusChanged signal.
*/
bool QDeclarativeDeviceInfo::monitorLockStatusChanges()
{
return monitoringLockStatusChanged;
}
/*!
This function starts the startLockStatusChanged notification.
*/
void QDeclarativeDeviceInfo::startLockStatusChanged(bool on)
{
monitoringLockStatusChanged = on;
if(on) {
connect(deviceInfo(),SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),
this,SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),
this,SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)));
}
}
/*!
\qmlproperty int DeviceInfo::messageRingtoneVolume()
Returns the active profile's message ringtone volume. From 0 to 100.
*/
int QDeclarativeDeviceInfo::messageRingtoneVolume()
{
return deviceInfo()->activeProfileDetails().messageRingtoneVolume();
}
/*!
\qmlproperty int DeviceInfo::voiceRingtoneVolume()
Returns the active profile's voice ringtone volume. From 0 to 100.
*/
int QDeclarativeDeviceInfo::voiceRingtoneVolume()
{
return deviceInfo()->activeProfileDetails().voiceRingtoneVolume();
}
/*!
\qmlproperty bool DeviceInfo::vibrationActive()
Returns the whether the active profile's vibration is active.
*/
bool QDeclarativeDeviceInfo::vibrationActive()
{
return deviceInfo()->activeProfileDetails().vibrationActive();
}
/*!
\qmlproperty bool DeviceInfo::primaryKeypadLightOn()
Returns the whether he primary keypad or keyboard light is on.
*/
/*!
Returns true if the primary key pad light is on, otherwise false;
*/
bool QDeclarativeDeviceInfo::primaryKeypadLightOn()
{
return deviceInfo()->keypadLightOn(QSystemDeviceInfo::PrimaryKeypad);
}
/*!
\qmlproperty bool DeviceInfo::secondaryKeypadLightOn()
Returns the whether he secondary keypad or keyboard light is on.
*/
/*!
Returns true if the key pad light is on, otherwise false;
*/
bool QDeclarativeDeviceInfo::secondaryKeypadLightOn()
{
return deviceInfo()->keypadLightOn(QSystemDeviceInfo::SecondaryKeypad);
}
/*!
\qmlproperty QString DeviceInfo::imei
Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.
*/
/*!
\qmlproperty QString DeviceInfo::imsi
Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none
*/
/*!
\qmlproperty QString DeviceInfo::manufacturer
Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor
of the motherboard.
*/
/*!
\qmlproperty QString DeviceInfo::model
Returns the model information of the device. In the case of desktops where no
model information is present, the CPU architect, such as i686, and machine type, such as Server,
Desktop or Laptop.
*/
/*!
\qmlproperty QString DeviceInfo::productName
Returns the product name of the device. In the case where no product information is available, an empty string will be returned.
*/
/*!
\qmlproperty int DeviceInfo::batteryLevel
Returns the battery charge level as percentage 1 - 100 scale.
*/
/*!
\qmlproperty InputMethodFlags DeviceInfo::inputMethodType
Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.
*/
/*!
\qmlproperty BatteryStatus DeviceInfo::batteryStatus
Returns the battery charge status.
*/
/*!
\qmlproperty bool DeviceInfo::isDeviceLocked
Returns true if the device is locked, otherwise false.
*/
/*!
\qmlproperty SimStatus DeviceInfo::simStatus
Returns the QSystemDeviceInfo::simStatus status of SIM card.
*/
/*!
\qmlproperty Profile DeviceInfo::currentProfile
Gets the current QSystemDeviceInfo::currentProfile device profile.
*/
/*!
\qmlproperty PowerState DeviceInfo::currentPowerState
Gets the current QSystemDeviceInfo::currentPowerState state.
*/
/*!
\qmlproperty bool DeviceInfo::currentBluetoothPowerState
Gets the current bluetooth power state.
*/
/*!
\qmlproperty KeyboardTypeFlags DeviceInfo::keyboardTypes
Returns the type of keyboards found.
*/
/*!
\qmlproperty bool DeviceInfo::isWirelessKeyboardConnected
Returns true if a wireless keyboard is connected, otherwise false;
*/
/*!
\qmlproperty bool DeviceInfo::isKeyboardFlippedOpen
Returns true if the flip keyboard is open, otherwise false;
*/
/*!
\qmlproperty LockTypeFlags DeviceInfo::lockStatus
Returns the QSystemDeviceInfo::LockTypeFlags type of lock state the device might be in.
The LockType must be currently active not just enabled.
*/
/*!
\qmlproperty string DeviceInfo::uniqueID
Returns a unique identifier for the machine.
Depending on security enforcement on platform, this may return a non unique number, or 0.
*/
<commit_msg>Docs: QTMOBILITY-1784. Added doc for currentThermalState<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativedeviceinfo_p.h"
#include "qsystemdeviceinfo.h"
#include <QMetaType>
#include <QDebug>
QT_BEGIN_NAMESPACE
Q_GLOBAL_STATIC(QSystemDeviceInfo, deviceInfo)
/*!
\qmlclass DeviceInfo QDeclarativeDeviceInfo
\brief The DeviceInfo element allows you to access information anbout the device and
receive notifications from the device.
\inherits QSystemDeviceInfo
\ingroup qml-systeminfo
This element is part of the \bold{QtMobility.systeminfo 1.1} module.
It is a convience class to make QML usage easier.
Note: To use notification signals, you need to set the monitor* properties to true.
\sa QSystemDeviceInfo
*/
/*!
\qmlsignal DeviceInfo::batteryLevelChanged(int)
This handler is called when battery level has changed.
*/
/*!
\qmlsignal DeviceInfo::batteryStatusChanged(DeviceInfo::BatteryStatus)
This handler is called when battery status has changed.
*/
/*!
\qmlsignal DeviceInfo::powerStateChanged(DeviceINfo::PowerState)
This handler is called when the power state has changed.
*/
/*!
\qmlsignal DeviceInfo::currentProfileChanged(DeviceInfo::Profile)
This handler is called when current device profile has changed.
*/
/*!
\qmlsignal DeviceInfo::bluetoothStateChanged(bool)
This handler is called when bluetooth power state has changed.
*/
/*!
\qmlsignal DeviceInfo::wirelessKeyboardConnected(bool)
This signal is emitted whenever a wireless keyboard is connected
*/
/*!
\qmlsignal DeviceInfo::keyboardFlipped(bool)
This signal is emitted whenever a phone flips open.
*/
/*!
\qmlsignal DeviceInfo::deviceLocked(bool)
This signal is emitted whenever the device lock state changes
*/
/*!
\qmlsignal DeviceInfo::lockStatusChanged(DeviceInfo::LockTypeFlags)
This signal is emitted whenever the lock state changes
*/
/*!
\qmlsignal DeviceInfo::thermalStateChanged(DeviceInfo::ThermalState)
This handler is called when thermal state has changed.
*/
QDeclarativeDeviceInfo::QDeclarativeDeviceInfo(QObject *parent) :
QSystemDeviceInfo(parent)
{
}
/*!
This function starts the batteryLevelChanged notification
*/
void QDeclarativeDeviceInfo::startBatteryLevelChanged(bool on)
{
monitoringBatteryLevel = on;
if(on) {
connect(deviceInfo(),SIGNAL(batteryLevelChanged(int)),
this,SIGNAL(batteryLevelChanged(int)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(batteryLevelChanged(int)),
this,SIGNAL(batteryLevelChanged(int)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorBatteryLevelChanges
Use the monitorBatteryLevelChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorBatteryLevelChanges()
{
return monitoringBatteryLevel;
}
/*!
This function starts the batteryStatusChanged notification
*/
void QDeclarativeDeviceInfo::startBatteryStatusChanged(bool on)
{
monitoringBatteryStatus = on;
if(on) {
connect(deviceInfo(),SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),
this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorBatteryStatusChanges
Use the monitorBatteryStatusChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorBatteryStatusChanges()
{
return monitoringBatteryStatus;
}
/*!
This function starts the powerStateChanged notification
*/
void QDeclarativeDeviceInfo::startPowerStateChanged(bool on)
{
monitoringPowerState = on;
if(on) {
connect(deviceInfo(),SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),
this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorPowerStateChanges
Use the monitorPowerStateChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorPowerStateChanges()
{
return monitoringPowerState;
}
/*!
This function is needed to start currentProfileChanged notification
*/
void QDeclarativeDeviceInfo::startCurrentProfileChanged(bool on)
{
monitoringCurrentProfile = on;
if(on) {
connect(deviceInfo(),SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),
this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorCurrentProfileChanges
Use the monitorCurrentProfileChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorCurrentProfileChanges()
{
return monitoringCurrentProfile;
}
/*!
This function starts the bluetoothStateChanged notification
*/
void QDeclarativeDeviceInfo::startBluetoothStateChanged(bool on)
{
monitorBluetoothState = on;
if(on) {
connect(deviceInfo(),SIGNAL(bluetoothStateChanged(bool)),
this,SIGNAL(bluetoothStateChanged(bool)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(bluetoothStateChanged(bool)),
this,SIGNAL(bluetoothStateChanged(bool)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorBluetoothStateChanges
Use the bluetoothStateChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorBluetoothStateChanges()
{
return monitorBluetoothState;
}
/*!
This function starts the thermalStateChanged notification
*/
void QDeclarativeDeviceInfo::startThermalStateChanged(bool on)
{
monitorThermalState = on;
if (on) {
connect(deviceInfo(), SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)),
this, SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)), Qt::UniqueConnection);
} else {
disconnect(deviceInfo(), SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)),
this, SIGNAL(thermalStateChanged(QSystemDeviceInfo::ThermalState)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorThermalStateChanges
Use the thermalStateChanges signal.
*/
bool QDeclarativeDeviceInfo::monitorThermalStateChanges()
{
return monitorThermalState;
}
/*!
\qmlproperty bool DeviceInfo::monitorWirelessKeyboardConnects()
Start the connection for the wirelessKeyboardConnected signal.
*/
bool QDeclarativeDeviceInfo::monitorWirelessKeyboardConnects()
{
return monitoringWirelessKeyboard;
}
/*!
This function starts the startBatteryStatusChanged notification.
*/
void QDeclarativeDeviceInfo::startWirelessKeyboardConnected(bool on)
{
monitoringWirelessKeyboard = on;
if(on) {
connect(deviceInfo(),SIGNAL(wirelessKeyboardConnected(bool)),
this,SIGNAL(wirelessKeyboardConnected(bool)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(wirelessKeyboardConnected(bool)),
this,SIGNAL(wirelessKeyboardConnected(bool)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorKeyboardFlips()
Start the connection for the keyboardFlipped signal.
*/
bool QDeclarativeDeviceInfo::monitorKeyboardFlips()
{
return monitoringKeyboardFlipped;
}
/*!
This function starts the startKeyboardFlipped notification.
*/
void QDeclarativeDeviceInfo::startKeyboardFlipped(bool on)
{
monitoringKeyboardFlipped = on;
if(on) {
connect(deviceInfo(),SIGNAL(keyboardFlipped(bool)),
this,SIGNAL(keyboardFlipped(bool)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(keyboardFlipped(bool)),
this,SIGNAL(keyboardFlipped(bool)));
}
}
/*!
\qmlproperty bool Device::monitorDeviceLocks()
Start the connection for the deviceLocked signal.
*/
bool QDeclarativeDeviceInfo::monitorDeviceLocks()
{
return monitoringDeviceLocked;
}
/*!
This function starts the startDeviceLocked notification.
*/
void QDeclarativeDeviceInfo::startDeviceLocked(bool on)
{
monitoringDeviceLocked = on;
if(on) {
connect(deviceInfo(),SIGNAL(deviceLocked(bool)),
this,SIGNAL(deviceLocked(bool)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(deviceLocked(bool)),
this,SIGNAL(deviceLocked(bool)));
}
}
/*!
\qmlproperty bool DeviceInfo::monitorLockStatusChanges()
Start the connection for the lockStatusChanged signal.
*/
bool QDeclarativeDeviceInfo::monitorLockStatusChanges()
{
return monitoringLockStatusChanged;
}
/*!
This function starts the startLockStatusChanged notification.
*/
void QDeclarativeDeviceInfo::startLockStatusChanged(bool on)
{
monitoringLockStatusChanged = on;
if(on) {
connect(deviceInfo(),SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),
this,SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),Qt::UniqueConnection);
} else {
disconnect(deviceInfo(),SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)),
this,SIGNAL(lockStatusChanged(QSystemDeviceInfo::LockTypeFlags)));
}
}
/*!
\qmlproperty int DeviceInfo::messageRingtoneVolume()
Returns the active profile's message ringtone volume. From 0 to 100.
*/
int QDeclarativeDeviceInfo::messageRingtoneVolume()
{
return deviceInfo()->activeProfileDetails().messageRingtoneVolume();
}
/*!
\qmlproperty int DeviceInfo::voiceRingtoneVolume()
Returns the active profile's voice ringtone volume. From 0 to 100.
*/
int QDeclarativeDeviceInfo::voiceRingtoneVolume()
{
return deviceInfo()->activeProfileDetails().voiceRingtoneVolume();
}
/*!
\qmlproperty bool DeviceInfo::vibrationActive()
Returns the whether the active profile's vibration is active.
*/
bool QDeclarativeDeviceInfo::vibrationActive()
{
return deviceInfo()->activeProfileDetails().vibrationActive();
}
/*!
\qmlproperty bool DeviceInfo::primaryKeypadLightOn()
Returns the whether he primary keypad or keyboard light is on.
*/
/*!
Returns true if the primary key pad light is on, otherwise false;
*/
bool QDeclarativeDeviceInfo::primaryKeypadLightOn()
{
return deviceInfo()->keypadLightOn(QSystemDeviceInfo::PrimaryKeypad);
}
/*!
\qmlproperty bool DeviceInfo::secondaryKeypadLightOn()
Returns the whether he secondary keypad or keyboard light is on.
*/
/*!
Returns true if the key pad light is on, otherwise false;
*/
bool QDeclarativeDeviceInfo::secondaryKeypadLightOn()
{
return deviceInfo()->keypadLightOn(QSystemDeviceInfo::SecondaryKeypad);
}
/*!
\qmlproperty QString DeviceInfo::imei
Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.
*/
/*!
\qmlproperty QString DeviceInfo::imsi
Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none
*/
/*!
\qmlproperty QString DeviceInfo::manufacturer
Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor
of the motherboard.
*/
/*!
\qmlproperty QString DeviceInfo::model
Returns the model information of the device. In the case of desktops where no
model information is present, the CPU architect, such as i686, and machine type, such as Server,
Desktop or Laptop.
*/
/*!
\qmlproperty QString DeviceInfo::productName
Returns the product name of the device. In the case where no product information is available, an empty string will be returned.
*/
/*!
\qmlproperty int DeviceInfo::batteryLevel
Returns the battery charge level as percentage 1 - 100 scale.
*/
/*!
\qmlproperty InputMethodFlags DeviceInfo::inputMethodType
Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.
*/
/*!
\qmlproperty BatteryStatus DeviceInfo::batteryStatus
Returns the battery charge status.
*/
/*!
\qmlproperty bool DeviceInfo::isDeviceLocked
Returns true if the device is locked, otherwise false.
*/
/*!
\qmlproperty SimStatus DeviceInfo::simStatus
Returns the QSystemDeviceInfo::simStatus status of SIM card.
*/
/*!
\qmlproperty Profile DeviceInfo::currentProfile
Gets the current QSystemDeviceInfo::currentProfile device profile.
*/
/*!
\qmlproperty PowerState DeviceInfo::currentPowerState
Gets the current QSystemDeviceInfo::currentPowerState state.
*/
/*!
\qmlproperty bool DeviceInfo::currentBluetoothPowerState
Gets the current bluetooth power state.
*/
/*!
\qmlproperty KeyboardTypeFlags DeviceInfo::keyboardTypes
Returns the type of keyboards found.
*/
/*!
\qmlproperty bool DeviceInfo::isWirelessKeyboardConnected
Returns true if a wireless keyboard is connected, otherwise false;
*/
/*!
\qmlproperty bool DeviceInfo::isKeyboardFlippedOpen
Returns true if the flip keyboard is open, otherwise false;
*/
/*!
\qmlproperty LockTypeFlags DeviceInfo::lockStatus
Returns the QSystemDeviceInfo::LockTypeFlags type of lock state the device might be in.
The LockType must be currently active not just enabled.
*/
/*!
\qmlproperty ThermalState DeviceInfo::currentThermalState
Returns the current thermal state of the device.
\since 1.2
\sa QSystemDeviceInfo::ThermalState
*/
/*!
\qmlproperty string DeviceInfo::uniqueID
Returns a unique identifier for the machine.
Depending on security enforcement on platform, this may return a non unique number, or 0.
*/
<|endoftext|>
|
<commit_before>#include <unordered_map>
#include <memory>
#include <glog/logging.h>
#include "streams.h"
#include "util.h"
#include <scheduler.h>
void call_rescue(e_t e, const children_t& children) {
for (auto& s: children) {
s(e);
}
}
stream_t prn() {
return [](e_t e) {
LOG(INFO) << "prn() " << event_to_json(e);
};
}
stream_t with(const with_changes_t& changes, const children_t& children) {
return [=](e_t e) {
Event ne(e);
for (auto &kv: changes) {
VLOG(3) << "with() first: " << kv.first << " second: " << kv.second;
set_event_value(ne, kv.first, kv.second, true);
}
call_rescue(ne, children);
};
}
stream_t with_ifempty(
const with_changes_t& changes,
const children_t& children)
{
return [=](e_t e) {
Event ne(e);
for (auto &kv: changes) {
VLOG(3) << "default() first: " << kv.first << " second: " << kv.second;
set_event_value(ne, kv.first, kv.second, false);
}
call_rescue(ne, children);
};
}
stream_t split(const split_clauses_t clauses,
const children_t& default_children)
{
return [=](e_t e) {
VLOG(3) << "split()";
for (auto const &pair: clauses) {
if (pair.first(e)) {
VLOG(3) << "split() clause found";
call_rescue(e, pair.second);
return;
}
}
if (default_children.size() > 0) {
VLOG(3) << "split() default";
call_rescue(e, default_children);
}
};
}
typedef std::unordered_map<std::string, const children_t> by_streams_map_t;
stream_t by(const by_keys_t& keys, const by_streams_t& streams) {
by_streams_map_t streams_map;
return [=](e_t e) mutable {
VLOG(3) << "by()";
if (keys.size() == 0) {
return;
}
std::string key("");
for (auto &k: keys) {
std::string value = string_to_value(e, k);
if (value == "__nil__") {
LOG(ERROR) << "by() field empty: " << k;
}
key += value + "-";
}
VLOG(3) << "by() key: " << key;
auto it = streams_map.find(key);
if (it == streams_map.end()) {
VLOG(3) << "by() key not found. Creating stream.";
children_t children;
for (auto &s: streams) {
children.push_back(s());
}
streams_map.insert({key, std::move(children)});
call_rescue(e, streams_map.find(key)->second);
} else {
VLOG(3) << "by() stream exists. ";
call_rescue(e, it->second);
}
};
}
stream_t where(const predicate_t& predicate, const children_t& children,
const children_t& else_children)
{
return [=](e_t e) {
if (predicate(e)) {
call_rescue(e, children);
} else {
call_rescue(e, else_children);
}
};
}
stream_t rate(const int interval, const children_t& children) {
std::shared_ptr<double> rate(std::make_shared<double>(0));
g_scheduler.add_periodic_task(
[=]() mutable
{
VLOG(3) << "rate-timer()";
Event e;
e.set_metric_f(*rate / interval);
e.set_time(time(0));
*rate = 0;
VLOG(3) << "rate-timer() value: " << e.metric_f();
call_rescue(e, children);
},
interval
);
return [=](e_t e) mutable {
VLOG(3) << "rate() rate += e.metric";
(*rate) += metric_to_double(e);
};
}
stream_t changed_state(std::string initial, const children_t& children) {
std::string last_state(initial);
return [=](e_t e) mutable {
VLOG(3) << "changed_state() last_state: "
<< last_state << " new state " << e.state();
if (last_state != e.state()) {
VLOG(3) << "changed_state() state change";
last_state.assign(e.state());
call_rescue(e, children);
}
};
}
stream_t tagged_any(const tags_t& tags, const children_t& children) {
return [=](e_t e) {
VLOG(3) << "tagged_any()";
if (tagged_any_(e, tags)) {
VLOG(3) << "tagged_any() match";
call_rescue(e, children);
}
};
}
stream_t tagged_all(const tags_t& tags, const children_t& children) {
return [=](e_t e) {
VLOG(3) << "tagged_all()";
if (tagged_all_(e, tags)) {
VLOG(3) << "tagged_all() match";
call_rescue(e, children);
}
};
}
bool tagged_any_(e_t e, const tags_t& tags) {
for (auto &tag: tags) {
if (tag_exists(e, tag)) {
return true;
}
}
return false;
}
bool tagged_all_(e_t e, const tags_t& tags) {
for (auto &tag: tags) {
if (!tag_exists(e, tag)) {
return false;
}
}
return true;
}
stream_t send_index(class index& idx) {
return [&](e_t e) {
if (e.state() != "expired") {
idx.add_event(e);
}
};
}
void streams::add_stream(stream_t stream) {
VLOG(3) << "adding stream";
streams_.push_back(stream);
}
void streams::process_message(const Msg& message) {
VLOG(3) << "process message. num of streams " << streams_.size();
unsigned long int sec = time(0);
for (int i = 0; i < message.events_size(); i++) {
const Event &event = message.events(i);
if (!event.has_time()) {
Event nevent(event);
nevent.set_time(sec);
push_event(std::move(nevent));
} else {
push_event(event);
}
}
}
void streams::push_event(const Event& e) {
for (auto& s: streams_) {
s(e);
}
}
<commit_msg>Refactor with and with_ifempty<commit_after>#include <unordered_map>
#include <memory>
#include <glog/logging.h>
#include "streams.h"
#include "util.h"
#include <scheduler.h>
void call_rescue(e_t e, const children_t& children) {
for (auto& s: children) {
s(e);
}
}
stream_t prn() {
return [](e_t e) {
LOG(INFO) << "prn() " << event_to_json(e);
};
}
stream_t with(const with_changes_t & changes,
const bool & replace,
const children_t & children)
{
return [=](e_t e) {
Event ne(e);
for (auto &kv: changes) {
set_event_value(ne, kv.first, kv.second, replace);
}
call_rescue(ne, children);
};
}
stream_t with(const with_changes_t& changes, const children_t& children) {
return with(changes, true, children);
}
stream_t with_ifempty(
const with_changes_t& changes,
const children_t& children)
{
return with(changes, false, children);
}
stream_t split(const split_clauses_t clauses,
const children_t& default_children)
{
return [=](e_t e) {
VLOG(3) << "split()";
for (auto const &pair: clauses) {
if (pair.first(e)) {
VLOG(3) << "split() clause found";
call_rescue(e, pair.second);
return;
}
}
if (default_children.size() > 0) {
VLOG(3) << "split() default";
call_rescue(e, default_children);
}
};
}
typedef std::unordered_map<std::string, const children_t> by_streams_map_t;
stream_t by(const by_keys_t& keys, const by_streams_t& streams) {
by_streams_map_t streams_map;
return [=](e_t e) mutable {
VLOG(3) << "by()";
if (keys.size() == 0) {
return;
}
std::string key("");
for (auto &k: keys) {
std::string value = string_to_value(e, k);
if (value == "__nil__") {
LOG(ERROR) << "by() field empty: " << k;
}
key += value + "-";
}
VLOG(3) << "by() key: " << key;
auto it = streams_map.find(key);
if (it == streams_map.end()) {
VLOG(3) << "by() key not found. Creating stream.";
children_t children;
for (auto &s: streams) {
children.push_back(s());
}
streams_map.insert({key, std::move(children)});
call_rescue(e, streams_map.find(key)->second);
} else {
VLOG(3) << "by() stream exists. ";
call_rescue(e, it->second);
}
};
}
stream_t where(const predicate_t& predicate, const children_t& children,
const children_t& else_children)
{
return [=](e_t e) {
if (predicate(e)) {
call_rescue(e, children);
} else {
call_rescue(e, else_children);
}
};
}
stream_t rate(const int interval, const children_t& children) {
std::shared_ptr<double> rate(std::make_shared<double>(0));
g_scheduler.add_periodic_task(
[=]() mutable
{
VLOG(3) << "rate-timer()";
Event e;
e.set_metric_f(*rate / interval);
e.set_time(time(0));
*rate = 0;
VLOG(3) << "rate-timer() value: " << e.metric_f();
call_rescue(e, children);
},
interval
);
return [=](e_t e) mutable {
VLOG(3) << "rate() rate += e.metric";
(*rate) += metric_to_double(e);
};
}
stream_t changed_state(std::string initial, const children_t& children) {
std::string last_state(initial);
return [=](e_t e) mutable {
VLOG(3) << "changed_state() last_state: "
<< last_state << " new state " << e.state();
if (last_state != e.state()) {
VLOG(3) << "changed_state() state change";
last_state.assign(e.state());
call_rescue(e, children);
}
};
}
stream_t tagged_any(const tags_t& tags, const children_t& children) {
return [=](e_t e) {
VLOG(3) << "tagged_any()";
if (tagged_any_(e, tags)) {
VLOG(3) << "tagged_any() match";
call_rescue(e, children);
}
};
}
stream_t tagged_all(const tags_t& tags, const children_t& children) {
return [=](e_t e) {
VLOG(3) << "tagged_all()";
if (tagged_all_(e, tags)) {
VLOG(3) << "tagged_all() match";
call_rescue(e, children);
}
};
}
bool tagged_any_(e_t e, const tags_t& tags) {
for (auto &tag: tags) {
if (tag_exists(e, tag)) {
return true;
}
}
return false;
}
bool tagged_all_(e_t e, const tags_t& tags) {
for (auto &tag: tags) {
if (!tag_exists(e, tag)) {
return false;
}
}
return true;
}
stream_t send_index(class index& idx) {
return [&](e_t e) {
if (e.state() != "expired") {
idx.add_event(e);
}
};
}
void streams::add_stream(stream_t stream) {
VLOG(3) << "adding stream";
streams_.push_back(stream);
}
void streams::process_message(const Msg& message) {
VLOG(3) << "process message. num of streams " << streams_.size();
unsigned long int sec = time(0);
for (int i = 0; i < message.events_size(); i++) {
const Event &event = message.events(i);
if (!event.has_time()) {
Event nevent(event);
nevent.set_time(sec);
push_event(std::move(nevent));
} else {
push_event(event);
}
}
}
void streams::push_event(const Event& e) {
for (auto& s: streams_) {
s(e);
}
}
<|endoftext|>
|
<commit_before>/*=============================================================================
Copyright (c) 2012-2013 Richard Otis
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// declaration for CompositionSet class
#ifndef COMPOSITIONSET_INCLUDED
#define COMPOSITIONSET_INCLUDED
#include "libgibbs/include/models.hpp"
#include "libgibbs/include/constraint.hpp"
#include "libgibbs/include/optimizer/ast_set.hpp"
#include "libgibbs/include/conditions.hpp"
#include "libgibbs/include/utils/ast_caching.hpp"
#include "libtdb/include/structure.hpp"
#include <memory>
#include <set>
#include <list>
#include <boost/bimap.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/vector.hpp>
// A CompositionSet works with libtdb's Phase class
// Its purpose is to handle the optimizer's specific configuration for the given conditions and models
// Multiple CompositionSets of the same Phase can be created to handle miscibility gaps
class CompositionSet {
public:
double evaluate_objective(evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
double evaluate_objective(evalconditions const &, std::map<std::string,double> const &) const;
std::map<int,double> evaluate_objective_gradient(
evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
std::map<int,double> evaluate_objective_gradient(
evalconditions const &, std::map<std::string,double> const &) const;
std::map<std::list<int>,double> evaluate_objective_hessian(
evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
boost::numeric::ublas::symmetric_matrix<double,boost::numeric::ublas::lower> evaluate_objective_hessian_matrix(
evalconditions const& conditions,
boost::bimap<std::string, int> const &main_indices,
std::vector<double> const &x) const;
std::set<std::list<int>> hessian_sparsity_structure(boost::bimap<std::string, int> const &) const;
std::vector<double> make_feasible_point(sublattice_set const &sublset, std::vector<double> const &x) const;
std::string name() const { return cset_name; }
// make CompositionSet from existing Phase
CompositionSet(
const Phase &phaseobj,
const parameter_set &pset,
const sublattice_set &sublset,
boost::bimap<std::string, int> const &main_indices);
CompositionSet() { }
CompositionSet(CompositionSet &&other) {
cset_name = std::move(other.cset_name);
models = std::move(other.models);
jac_g_trees = std::move(other.jac_g_trees);
hessian_data = std::move(other.hessian_data);
tree_data = std::move(other.tree_data);
first_derivatives = std::move(other.first_derivatives);
symbols = std::move(other.symbols);
cm = std::move(other.cm);
phase_indices = std::move(other.phase_indices);
constraint_null_space_matrix = std::move(other.constraint_null_space_matrix);
constraint_particular_solution = std::move(other.constraint_particular_solution);
}
CompositionSet& operator=(CompositionSet &&other) {
cset_name = std::move(other.cset_name);
models = std::move(other.models);
jac_g_trees = std::move(other.jac_g_trees);
hessian_data = std::move(other.hessian_data);
tree_data = std::move(other.tree_data);
first_derivatives = std::move(other.first_derivatives);
symbols = std::move(other.symbols);
cm = std::move(other.cm);
phase_indices = std::move(other.phase_indices);
constraint_null_space_matrix = std::move(other.constraint_null_space_matrix);
constraint_particular_solution = std::move(other.constraint_particular_solution);
}
const std::vector<jacobian_entry>& get_jacobian() const { return jac_g_trees; };
const std::vector<Constraint>& get_constraints() const { return cm.constraints; };
const boost::bimap<std::string, int>& get_variable_map() const { return phase_indices; };
const boost::numeric::ublas::matrix<double>& get_constraint_null_space_matrix() const { return constraint_null_space_matrix; };
const ASTSymbolMap& get_symbols() const { return symbols; };
CompositionSet(const CompositionSet &) = delete;
CompositionSet& operator=(const CompositionSet &) = delete;
private:
std::string cset_name;
std::map<std::string,std::unique_ptr<EnergyModel>> models;
std::map<int,boost::spirit::utree> first_derivatives;
boost::bimap<std::string, int> phase_indices;
std::vector<jacobian_entry> jac_g_trees;
hessian_set hessian_data;
ast_set tree_data;
ASTSymbolMap symbols; // maps special symbols to ASTs and their derivatives
ConstraintManager cm; // handles constraints internal to the phase, e.g., site fraction balances
void build_constraint_basis_matrices(sublattice_set const &sublset);
boost::numeric::ublas::matrix<double> constraint_null_space_matrix;
boost::numeric::ublas::vector<double> constraint_particular_solution;
};
#endif
<commit_msg>Added constraint_extents member<commit_after>/*=============================================================================
Copyright (c) 2012-2014 Richard Otis
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
// declaration for CompositionSet class
#ifndef COMPOSITIONSET_INCLUDED
#define COMPOSITIONSET_INCLUDED
#include "libgibbs/include/models.hpp"
#include "libgibbs/include/constraint.hpp"
#include "libgibbs/include/optimizer/ast_set.hpp"
#include "libgibbs/include/conditions.hpp"
#include "libgibbs/include/utils/ast_caching.hpp"
#include "libtdb/include/structure.hpp"
#include <boost/bimap.hpp>
#include <boost/numeric/ublas/symmetric.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <memory>
#include <set>
#include <list>
#include <vector>
#include <utility>
// A CompositionSet works with libtdb's Phase class
// Its purpose is to handle the optimizer's specific configuration for the given conditions and models
// Multiple CompositionSets of the same Phase can be created to handle miscibility gaps
class CompositionSet {
public:
double evaluate_objective(evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
double evaluate_objective(evalconditions const &, std::map<std::string,double> const &) const;
std::map<int,double> evaluate_objective_gradient(
evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
std::map<int,double> evaluate_objective_gradient(
evalconditions const &, std::map<std::string,double> const &) const;
std::map<std::list<int>,double> evaluate_objective_hessian(
evalconditions const&, boost::bimap<std::string, int> const &, double* const) const;
boost::numeric::ublas::symmetric_matrix<double,boost::numeric::ublas::lower> evaluate_objective_hessian_matrix(
evalconditions const& conditions,
boost::bimap<std::string, int> const &main_indices,
std::vector<double> const &x) const;
std::set<std::list<int>> hessian_sparsity_structure(boost::bimap<std::string, int> const &) const;
std::vector<double> make_feasible_point(sublattice_set const &sublset, std::vector<double> const &x) const;
std::string name() const { return cset_name; }
// make CompositionSet from existing Phase
CompositionSet(
const Phase &phaseobj,
const parameter_set &pset,
const sublattice_set &sublset,
boost::bimap<std::string, int> const &main_indices);
CompositionSet() { }
CompositionSet(CompositionSet &&other) {
cset_name = std::move(other.cset_name);
models = std::move(other.models);
jac_g_trees = std::move(other.jac_g_trees);
hessian_data = std::move(other.hessian_data);
tree_data = std::move(other.tree_data);
first_derivatives = std::move(other.first_derivatives);
symbols = std::move(other.symbols);
cm = std::move(other.cm);
phase_indices = std::move(other.phase_indices);
constraint_null_space_matrix = std::move(other.constraint_null_space_matrix);
constraint_particular_solution = std::move(other.constraint_particular_solution);
constraint_extents = std::move(other.constraint_extents);
}
CompositionSet& operator=(CompositionSet &&other) {
cset_name = std::move(other.cset_name);
models = std::move(other.models);
jac_g_trees = std::move(other.jac_g_trees);
hessian_data = std::move(other.hessian_data);
tree_data = std::move(other.tree_data);
first_derivatives = std::move(other.first_derivatives);
symbols = std::move(other.symbols);
cm = std::move(other.cm);
phase_indices = std::move(other.phase_indices);
constraint_null_space_matrix = std::move(other.constraint_null_space_matrix);
constraint_particular_solution = std::move(other.constraint_particular_solution);
constraint_extents = std::move(other.constraint_extents);
}
const std::vector<jacobian_entry>& get_jacobian() const { return jac_g_trees; };
const std::vector<Constraint>& get_constraints() const { return cm.constraints; };
const boost::bimap<std::string, int>& get_variable_map() const { return phase_indices; };
const boost::numeric::ublas::matrix<double>& get_constraint_null_space_matrix() const { return constraint_null_space_matrix; };
const std::vector<std::pair<double,double> >& get_constraint_extents() const { return constraint_extents; };
const ASTSymbolMap& get_symbols() const { return symbols; };
CompositionSet(const CompositionSet &) = delete;
CompositionSet& operator=(const CompositionSet &) = delete;
private:
std::string cset_name;
std::map<std::string,std::unique_ptr<EnergyModel>> models;
std::map<int,boost::spirit::utree> first_derivatives;
boost::bimap<std::string, int> phase_indices;
std::vector<jacobian_entry> jac_g_trees;
hessian_set hessian_data;
ast_set tree_data;
ASTSymbolMap symbols; // maps special symbols to ASTs and their derivatives
ConstraintManager cm; // handles constraints internal to the phase, e.g., site fraction balances
void build_constraint_basis_matrices(sublattice_set const &sublset);
boost::numeric::ublas::matrix<double> constraint_null_space_matrix;
boost::numeric::ublas::vector<double> constraint_particular_solution;
std::vector<std::pair<double,double> > constraint_extents;
};
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <graphene/protocol/fee_schedule.hpp>
#include <fc/io/raw.hpp>
#define MAX_FEE_STABILIZATION_ITERATION 4
namespace graphene { namespace protocol {
fee_schedule::fee_schedule()
{
}
fee_schedule fee_schedule::get_default()
{
fee_schedule result;
for( int i = 0; i < fee_parameters().count(); ++i )
{
fee_parameters x; x.set_which(i);
result.parameters.insert(x);
}
return result;
}
struct set_fee_visitor
{
typedef void result_type;
asset _fee;
set_fee_visitor( asset f ):_fee(f){}
template<typename OpType>
void operator()( OpType& op )const
{
op.fee = _fee;
}
};
struct zero_fee_visitor
{
typedef void result_type;
template<typename ParamType>
result_type operator()( ParamType& op )const
{
memset( (char*)&op, 0, sizeof(op) );
}
};
void fee_schedule::zero_all_fees()
{
*this = get_default();
for( fee_parameters& i : parameters )
i.visit( zero_fee_visitor() );
this->scale = 0;
}
asset fee_schedule::set_fee( operation& op, const price& core_exchange_rate )const
{
auto f = calculate_fee( op, core_exchange_rate );
auto f_max = f;
for( int i=0; i<MAX_FEE_STABILIZATION_ITERATION; i++ )
{
op.visit( set_fee_visitor( f_max ) );
auto f2 = calculate_fee( op, core_exchange_rate );
if( f == f2 )
break;
f_max = std::max( f_max, f2 );
f = f2;
if( i == 0 )
{
// no need for warnings on later iterations
wlog( "set_fee requires multiple iterations to stabilize with core_exchange_rate ${p} on operation ${op}",
("p", core_exchange_rate) ("op", op) );
}
}
return f_max;
}
void chain_parameters::validate()const
{
get_current_fees().validate();
FC_ASSERT( reserve_percent_of_fee <= GRAPHENE_100_PERCENT );
FC_ASSERT( network_percent_of_fee <= GRAPHENE_100_PERCENT );
FC_ASSERT( lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT );
FC_ASSERT( network_percent_of_fee + lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT );
FC_ASSERT( block_interval >= GRAPHENE_MIN_BLOCK_INTERVAL );
FC_ASSERT( block_interval <= GRAPHENE_MAX_BLOCK_INTERVAL );
FC_ASSERT( block_interval > 0 );
FC_ASSERT( maintenance_interval > block_interval,
"Maintenance interval must be longer than block interval" );
FC_ASSERT( maintenance_interval % block_interval == 0,
"Maintenance interval must be a multiple of block interval" );
FC_ASSERT( maximum_transaction_size >= GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT,
"Transaction size limit is too low" );
FC_ASSERT( maximum_block_size >= GRAPHENE_MIN_BLOCK_SIZE_LIMIT,
"Block size limit is too low" );
FC_ASSERT( maximum_time_until_expiration > block_interval,
"Maximum transaction expiration time must be greater than a block interval" );
FC_ASSERT( maximum_proposal_lifetime - committee_proposal_review_period > block_interval,
"Committee proposal review period must be less than the maximum proposal lifetime" );
}
} } // graphene::protocol
<commit_msg>Fix compiler warnings<commit_after>/*
* Copyright (c) 2015 Cryptonomex, Inc., and contributors.
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <algorithm>
#include <graphene/protocol/fee_schedule.hpp>
#include <fc/io/raw.hpp>
#define MAX_FEE_STABILIZATION_ITERATION 4
namespace graphene { namespace protocol {
fee_schedule::fee_schedule()
{
}
fee_schedule fee_schedule::get_default()
{
fee_schedule result;
for( size_t i = 0; i < fee_parameters().count(); ++i )
{
fee_parameters x; x.set_which(i);
result.parameters.insert(x);
}
return result;
}
struct set_fee_visitor
{
typedef void result_type;
asset _fee;
set_fee_visitor( asset f ):_fee(f){}
template<typename OpType>
void operator()( OpType& op )const
{
op.fee = _fee;
}
};
struct zero_fee_visitor
{
typedef void result_type;
template<typename ParamType>
result_type operator()( ParamType& op )const
{
memset( (char*)&op, 0, sizeof(op) );
}
};
void fee_schedule::zero_all_fees()
{
*this = get_default();
for( fee_parameters& i : parameters )
i.visit( zero_fee_visitor() );
this->scale = 0;
}
asset fee_schedule::set_fee( operation& op, const price& core_exchange_rate )const
{
auto f = calculate_fee( op, core_exchange_rate );
auto f_max = f;
for( size_t i=0; i<MAX_FEE_STABILIZATION_ITERATION; i++ )
{
op.visit( set_fee_visitor( f_max ) );
auto f2 = calculate_fee( op, core_exchange_rate );
if( f == f2 )
break;
f_max = std::max( f_max, f2 );
f = f2;
if( i == 0 )
{
// no need for warnings on later iterations
wlog( "set_fee requires multiple iterations to stabilize with core_exchange_rate ${p} on operation ${op}",
("p", core_exchange_rate) ("op", op) );
}
}
return f_max;
}
void chain_parameters::validate()const
{
get_current_fees().validate();
FC_ASSERT( reserve_percent_of_fee <= GRAPHENE_100_PERCENT );
FC_ASSERT( network_percent_of_fee <= GRAPHENE_100_PERCENT );
FC_ASSERT( lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT );
FC_ASSERT( network_percent_of_fee + lifetime_referrer_percent_of_fee <= GRAPHENE_100_PERCENT );
FC_ASSERT( block_interval >= GRAPHENE_MIN_BLOCK_INTERVAL );
FC_ASSERT( block_interval <= GRAPHENE_MAX_BLOCK_INTERVAL );
FC_ASSERT( block_interval > 0 );
FC_ASSERT( maintenance_interval > block_interval,
"Maintenance interval must be longer than block interval" );
FC_ASSERT( maintenance_interval % block_interval == 0,
"Maintenance interval must be a multiple of block interval" );
FC_ASSERT( maximum_transaction_size >= GRAPHENE_MIN_TRANSACTION_SIZE_LIMIT,
"Transaction size limit is too low" );
FC_ASSERT( maximum_block_size >= GRAPHENE_MIN_BLOCK_SIZE_LIMIT,
"Block size limit is too low" );
FC_ASSERT( maximum_time_until_expiration > block_interval,
"Maximum transaction expiration time must be greater than a block interval" );
FC_ASSERT( maximum_proposal_lifetime - committee_proposal_review_period > block_interval,
"Committee proposal review period must be less than the maximum proposal lifetime" );
}
} } // graphene::protocol
<|endoftext|>
|
<commit_before>/*
* File: tileSet.cpp
*
* Description: Implements TileSet class
*/
#include <tileSet.hpp>
// No params constructor method for TileSet
TileSet::TileSet() {
}
// Constructor method for TileSet
// Recivies the integer w, that represents the width of a tile
// Recivies the integer h, that represents the height of a tile
// Recivies the string file, that represents file path
TileSet::TileSet(int w, int h, string file) {
Load(w, h, file);
}
// Loads the tileset from the file
// Recivies the integer w, that represents the width of a tile
// Recivies the integer h, that represents the height of a tile
// Recivies the string file, that represents file path
void TileSet::Load(int w, int h, string file) {
// Attributes the value of the width and height of a tile
tileWidth = w;
tileHeight = h;
// Opens the file with the tileSet
tileSet.Open(file);
// Defines the numbers of rows and columns of the tileSet
rows = tileSet.GetHeight()/tileHeight;
columns = tileSet.GetWidth()/tileWidth;
}
// Render the tileSet
void TileSet::Render(unsigned int index,float x,float y, float extScale) {
if ((int)index<(rows*columns)) {
tileSet.SetClip(tileWidth*(index%columns),(tileHeight*(index/columns)),
tileWidth,tileHeight);
tileSet.Render(x,y,0,extScale);
}
// TODO: else (do nothing)
}
// Returns the width of the TileSet
int TileSet::GetWidth() {
return tileWidth;
}
// Returns the height of the TileSet
int TileSet::GetHeight() {
return tileHeight;
}
// Returns the number of tiles in the tileSet
int TileSet::GetTileCount() {
return rows*columns;
}
<commit_msg>Refactories commentaries technique at file tileSet.cpp<commit_after>/*!
* \file File tileSet.cpp
* \brief Implementation of the class TileSet
*
* Auxiliary documentation
* \sa tileSet.hpp
*/
#include <tileSet.hpp>
/*!
@class TileSet
@brief This class provides the tile sets to the game
*/
//! A constructor.
/*!
This is a empty constructor method of TileSet class
*/
TileSet::TileSet() {
}
//! A constructor.
/*!
* This is a constructor method of TileSet class
* \param w
* \brief A positive integer, that represents width of a tile
* \param h
* \brief A positive integer, that represents height of a tile
* \param file
* \brief A string, that represents path of the file with the tile set
*/
TileSet::TileSet(int w, int h, string file) {
Load(w, h, file);
}
/*!
@fn void TileSet::Load(int w, int h, string file)
@brief Method that loads the tile set from the file
@param w
@brief A positive integer, that represents width of a tile
@param h
@brief A positive integer, that represents height of a tile
@param file
@brief A string, that represents path of the file with the tile set
@return The execution of this method returns no value
*/
void TileSet::Load(int w, int h, string file) {
//! Attributes the value of the width and height of a tile
tileWidth = w;
tileHeight = h;
//! Opens the file with the tile set
tileSet.Open(file);
//! Defines the numbers of rows and columns of the tile set
rows = tileSet.GetHeight() / tileHeight;
columns = tileSet.GetWidth() / tileWidth;
}
/*!
@fn void TileSet::Render(unsigned int index, float x, float y, float extScale)
@brief Method that renders the tile set
@param index
@brief A unsigned integer
@param x
@brief A float
@param y
@brief A float
@param extScale
@brief A float
@return The execution of this method returns no value
@warning Method that requires review of comment
*/
void TileSet::Render(unsigned int index, float x, float y, float extScale) {
//! Checks if the number of tiles is bigger that the index
if ((int)index < (rows * columns)) {
tileSet.SetClip(tileWidth * (index % columns),
(tileHeight * (index / columns)), tileWidth, tileHeight);
tileSet.Render(x, y, 0, extScale);
}
//! \warning else (do nothing)
}
/*!
@fn int TileSet::GetWidth()
@brief A getter of the attribute tileWidth
@return A positive integer, that represents the width of a tile
*/
int TileSet::GetWidth() {
return tileWidth;
}
/*!
@fn int TileSet::GetHeight()
@brief A getter of the attribute tileHeight
@return A positive integer, that represents the height of a tile
*/
int TileSet::GetHeight() {
return tileHeight;
}
/*!
@fn int TileSet::GetTileCount()
@brief Method that returns the number of tiles in the tile set
@return A positive integer, that number of tiles in the tile set
*/
int TileSet::GetTileCount() {
return rows*columns;
}
<|endoftext|>
|
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* 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 "generatorBase/robotsGeneratorPluginBase.h"
#include <QtCore/QDateTime>
#include <qrkernel/platformInfo.h>
#include <qrutils/inFile.h>
#include <qrutils/nameNormalizer.h>
#include <qrutils/parserErrorReporter.h>
#include <qrgui/textEditor/qscintillaTextEdit.h>
using namespace generatorBase;
using namespace qReal;
using namespace utils;
/// If file info creation and modification timestamps differ less than on this value it is considered
/// that file was created and filled at the same time.
const int maxTimestampsDifference = 3000;
RobotsGeneratorPluginBase::RobotsGeneratorPluginBase()
{
}
RobotsGeneratorPluginBase::~RobotsGeneratorPluginBase()
{
}
QString RobotsGeneratorPluginBase::defaultFilePath(const QString &projectName) const
{
return projectName;
}
QString RobotsGeneratorPluginBase::generatorName() const
{
return QString();
}
QString RobotsGeneratorPluginBase::defaultProjectName() const
{
const QString filePath = mProjectManager->saveFilePath();
return filePath.isEmpty() ? "example" : QFileInfo(filePath).completeBaseName();
}
bool RobotsGeneratorPluginBase::canGenerateTo(const QString &project)
{
const QFileInfo fileInfo = generationTarget(project);
const int difference = fileInfo.lastModified().toMSecsSinceEpoch() - fileInfo.created().toMSecsSinceEpoch();
return !fileInfo.exists() || difference < maxTimestampsDifference;
}
void RobotsGeneratorPluginBase::onCurrentRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)
{
if (robotModels().count() == 1) {
kitBase::robotModel::RobotModelInterface * const ourModel = robotModels()[0];;
for (const ActionInfo &action : customActions()) {
if (action.isAction()) {
action.action()->setVisible(ourModel == &model);
} else {
action.menu()->setVisible(ourModel == &model);
}
}
}
}
void RobotsGeneratorPluginBase::onCurrentDiagramChanged(const TabInfo &info)
{
const bool enabled = info.type() == TabInfo::TabType::code || info.type() == TabInfo::TabType::editor;
for (const ActionInfo &action : customActions()) {
if (action.isAction()) {
action.action()->setEnabled(enabled);
} else {
action.menu()->setEnabled(enabled);
}
}
}
QFileInfo RobotsGeneratorPluginBase::generationTarget(const QString &pathFromRoot) const
{
return QFileInfo(PlatformInfo::invariantSettingsPath("pathToGeneratorRoot") + "/" + defaultFilePath(pathFromRoot));
}
QFileInfo RobotsGeneratorPluginBase::srcPath()
{
const Id &activeDiagram = mMainWindowInterface->activeDiagram();
int exampleNumber = 0;
QString projectName;
do {
projectName = NameNormalizer::normalizeStrongly(defaultProjectName(), false)
+ (exampleNumber > 0 ? QString::number(exampleNumber) : "");
++exampleNumber;
} while (!canGenerateTo(projectName));
QFileInfo fileInfo = generationTarget(projectName);
const QList<QFileInfo> pathsList = mCodePath.values(activeDiagram);
if (!pathsList.isEmpty()) {
for (const QFileInfo &path : pathsList) {
if (mTextManager->isDefaultPath(path.absoluteFilePath())
&& !mTextManager->isModifiedEver(path.absoluteFilePath())
&& !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName()))
{
fileInfo = path;
break;
}
}
}
return fileInfo;
}
QFileInfo RobotsGeneratorPluginBase::generateCodeForProcessing()
{
QFileInfo fileInfo;
const Id &activeDiagram = mMainWindowInterface->activeDiagram();
if (!activeDiagram.isNull()) {
if (generateCode(false)) {
for (const QFileInfo &path : mCodePath.values(activeDiagram)) {
if (mTextManager->isDefaultPath(path.absoluteFilePath())
&& (!mTextManager->isModifiedEver(path.absoluteFilePath()))
&& !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName()))
{
fileInfo = path;
break;
}
}
} else {
return QFileInfo();
}
} else if (auto code = dynamic_cast<text::QScintillaTextEdit *>(mMainWindowInterface->currentTab())) {
fileInfo = QFileInfo(mTextManager->path(code));
mTextManager->saveText(false);
}
return fileInfo;
}
void RobotsGeneratorPluginBase::init(const kitBase::KitPluginConfigurator &configurator)
{
mProjectManager = &configurator.qRealConfigurator().projectManager();
mSystemEvents = &configurator.qRealConfigurator().systemEvents();
mTextManager = &configurator.qRealConfigurator().textManager();
mMainWindowInterface = &configurator.qRealConfigurator().mainWindowInterpretersInterface();
mRepo = dynamic_cast<const qrRepo::RepoApi *>(&configurator.qRealConfigurator().logicalModelApi().logicalRepoApi());
mProjectManager = &configurator.qRealConfigurator().projectManager();
mRobotModelManager = &configurator.robotModelManager();
mTextLanguage = &configurator.textLanguage();
mParserErrorReporter.reset(new ParserErrorReporter(*mTextLanguage, *mMainWindowInterface->errorReporter()
, configurator.qRealConfigurator().logicalModelApi().editorManagerInterface()));
connect(mSystemEvents, SIGNAL(codePathChanged(qReal::Id, QFileInfo, QFileInfo))
, this, SLOT(regenerateCode(qReal::Id, QFileInfo, QFileInfo)));
connect(mSystemEvents, SIGNAL(newCodeAppeared(qReal::Id, QFileInfo)), this, SLOT(addNewCode(qReal::Id, QFileInfo)));
connect(mSystemEvents, SIGNAL(diagramClosed(qReal::Id)), this, SLOT(removeDiagram(qReal::Id)));
connect(mSystemEvents, SIGNAL(codeTabClosed(QFileInfo)), this, SLOT(removeCode(QFileInfo)));
connect(mRobotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged
, this, &RobotsGeneratorPluginBase::onCurrentRobotModelChanged);
connect(mSystemEvents, &SystemEvents::activeTabChanged, this, &RobotsGeneratorPluginBase::onCurrentDiagramChanged);
}
QString RobotsGeneratorPluginBase::friendlyKitName() const
{
// Kit friendly name is already defined in interpreter kit plugins.
return QString();
}
bool RobotsGeneratorPluginBase::generateCode(bool openTab)
{
mProjectManager->save();
/// @todo: clearErrors() and clear() are absolutely different methods without documentation - wtf?
mMainWindowInterface->errorReporter()->clearErrors();
mMainWindowInterface->errorReporter()->clear();
MasterGeneratorBase * const generator = masterGenerator();
const QFileInfo path = srcPath();
generator->initialize();
generator->setProjectDir(path);
const QString generatedSrcPath = generator->generate(language().indent());
if (mMainWindowInterface->errorReporter()->wereErrors()) {
delete generator;
return false;
}
const Id activeDiagram = mMainWindowInterface->activeDiagram();
const QString generatedCode = utils::InFile::readAll(generatedSrcPath);
if (!generatedCode.isEmpty()) {
mTextManager->showInTextEditor(path, generatorName(), language());
}
if (!openTab) {
mMainWindowInterface->activateItemOrDiagram(activeDiagram);
}
delete generator;
return true;
}
void RobotsGeneratorPluginBase::regenerateCode(const qReal::Id &diagram
, const QFileInfo &oldFileInfo
, const QFileInfo &newFileInfo)
{
if (!oldFileInfo.completeSuffix().compare(language().extension)) {
mCodePath.remove(diagram, oldFileInfo);
mCodePath.insert(diagram, newFileInfo);
regenerateExtraFiles(newFileInfo);
}
}
void RobotsGeneratorPluginBase::addNewCode(const Id &diagram, const QFileInfo &fileInfo)
{
mCodePath.insert(diagram, fileInfo);
}
void RobotsGeneratorPluginBase::removeDiagram(const qReal::Id &diagram)
{
mCodePath.remove(diagram);
}
void RobotsGeneratorPluginBase::removeCode(const QFileInfo &fileInfo)
{
const Id &diagram = mCodePath.key(fileInfo);
mCodePath.remove(diagram, fileInfo);
}
<commit_msg>Fix redundant semicolon<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* 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 "generatorBase/robotsGeneratorPluginBase.h"
#include <QtCore/QDateTime>
#include <qrkernel/platformInfo.h>
#include <qrutils/inFile.h>
#include <qrutils/nameNormalizer.h>
#include <qrutils/parserErrorReporter.h>
#include <qrgui/textEditor/qscintillaTextEdit.h>
using namespace generatorBase;
using namespace qReal;
using namespace utils;
/// If file info creation and modification timestamps differ less than on this value it is considered
/// that file was created and filled at the same time.
const int maxTimestampsDifference = 3000;
RobotsGeneratorPluginBase::RobotsGeneratorPluginBase()
{
}
RobotsGeneratorPluginBase::~RobotsGeneratorPluginBase()
{
}
QString RobotsGeneratorPluginBase::defaultFilePath(const QString &projectName) const
{
return projectName;
}
QString RobotsGeneratorPluginBase::generatorName() const
{
return QString();
}
QString RobotsGeneratorPluginBase::defaultProjectName() const
{
const QString filePath = mProjectManager->saveFilePath();
return filePath.isEmpty() ? "example" : QFileInfo(filePath).completeBaseName();
}
bool RobotsGeneratorPluginBase::canGenerateTo(const QString &project)
{
const QFileInfo fileInfo = generationTarget(project);
const int difference = fileInfo.lastModified().toMSecsSinceEpoch() - fileInfo.created().toMSecsSinceEpoch();
return !fileInfo.exists() || difference < maxTimestampsDifference;
}
void RobotsGeneratorPluginBase::onCurrentRobotModelChanged(kitBase::robotModel::RobotModelInterface &model)
{
if (robotModels().count() == 1) {
kitBase::robotModel::RobotModelInterface * const ourModel = robotModels()[0];
for (const ActionInfo &action : customActions()) {
if (action.isAction()) {
action.action()->setVisible(ourModel == &model);
} else {
action.menu()->setVisible(ourModel == &model);
}
}
}
}
void RobotsGeneratorPluginBase::onCurrentDiagramChanged(const TabInfo &info)
{
const bool enabled = info.type() == TabInfo::TabType::code || info.type() == TabInfo::TabType::editor;
for (const ActionInfo &action : customActions()) {
if (action.isAction()) {
action.action()->setEnabled(enabled);
} else {
action.menu()->setEnabled(enabled);
}
}
}
QFileInfo RobotsGeneratorPluginBase::generationTarget(const QString &pathFromRoot) const
{
return QFileInfo(PlatformInfo::invariantSettingsPath("pathToGeneratorRoot") + "/" + defaultFilePath(pathFromRoot));
}
QFileInfo RobotsGeneratorPluginBase::srcPath()
{
const Id &activeDiagram = mMainWindowInterface->activeDiagram();
int exampleNumber = 0;
QString projectName;
do {
projectName = NameNormalizer::normalizeStrongly(defaultProjectName(), false)
+ (exampleNumber > 0 ? QString::number(exampleNumber) : "");
++exampleNumber;
} while (!canGenerateTo(projectName));
QFileInfo fileInfo = generationTarget(projectName);
const QList<QFileInfo> pathsList = mCodePath.values(activeDiagram);
if (!pathsList.isEmpty()) {
for (const QFileInfo &path : pathsList) {
if (mTextManager->isDefaultPath(path.absoluteFilePath())
&& !mTextManager->isModifiedEver(path.absoluteFilePath())
&& !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName()))
{
fileInfo = path;
break;
}
}
}
return fileInfo;
}
QFileInfo RobotsGeneratorPluginBase::generateCodeForProcessing()
{
QFileInfo fileInfo;
const Id &activeDiagram = mMainWindowInterface->activeDiagram();
if (!activeDiagram.isNull()) {
if (generateCode(false)) {
for (const QFileInfo &path : mCodePath.values(activeDiagram)) {
if (mTextManager->isDefaultPath(path.absoluteFilePath())
&& (!mTextManager->isModifiedEver(path.absoluteFilePath()))
&& !mTextManager->generatorName(path.absoluteFilePath()).compare(generatorName()))
{
fileInfo = path;
break;
}
}
} else {
return QFileInfo();
}
} else if (auto code = dynamic_cast<text::QScintillaTextEdit *>(mMainWindowInterface->currentTab())) {
fileInfo = QFileInfo(mTextManager->path(code));
mTextManager->saveText(false);
}
return fileInfo;
}
void RobotsGeneratorPluginBase::init(const kitBase::KitPluginConfigurator &configurator)
{
mProjectManager = &configurator.qRealConfigurator().projectManager();
mSystemEvents = &configurator.qRealConfigurator().systemEvents();
mTextManager = &configurator.qRealConfigurator().textManager();
mMainWindowInterface = &configurator.qRealConfigurator().mainWindowInterpretersInterface();
mRepo = dynamic_cast<const qrRepo::RepoApi *>(&configurator.qRealConfigurator().logicalModelApi().logicalRepoApi());
mProjectManager = &configurator.qRealConfigurator().projectManager();
mRobotModelManager = &configurator.robotModelManager();
mTextLanguage = &configurator.textLanguage();
mParserErrorReporter.reset(new ParserErrorReporter(*mTextLanguage, *mMainWindowInterface->errorReporter()
, configurator.qRealConfigurator().logicalModelApi().editorManagerInterface()));
connect(mSystemEvents, SIGNAL(codePathChanged(qReal::Id, QFileInfo, QFileInfo))
, this, SLOT(regenerateCode(qReal::Id, QFileInfo, QFileInfo)));
connect(mSystemEvents, SIGNAL(newCodeAppeared(qReal::Id, QFileInfo)), this, SLOT(addNewCode(qReal::Id, QFileInfo)));
connect(mSystemEvents, SIGNAL(diagramClosed(qReal::Id)), this, SLOT(removeDiagram(qReal::Id)));
connect(mSystemEvents, SIGNAL(codeTabClosed(QFileInfo)), this, SLOT(removeCode(QFileInfo)));
connect(mRobotModelManager, &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged
, this, &RobotsGeneratorPluginBase::onCurrentRobotModelChanged);
connect(mSystemEvents, &SystemEvents::activeTabChanged, this, &RobotsGeneratorPluginBase::onCurrentDiagramChanged);
}
QString RobotsGeneratorPluginBase::friendlyKitName() const
{
// Kit friendly name is already defined in interpreter kit plugins.
return QString();
}
bool RobotsGeneratorPluginBase::generateCode(bool openTab)
{
mProjectManager->save();
/// @todo: clearErrors() and clear() are absolutely different methods without documentation - wtf?
mMainWindowInterface->errorReporter()->clearErrors();
mMainWindowInterface->errorReporter()->clear();
MasterGeneratorBase * const generator = masterGenerator();
const QFileInfo path = srcPath();
generator->initialize();
generator->setProjectDir(path);
const QString generatedSrcPath = generator->generate(language().indent());
if (mMainWindowInterface->errorReporter()->wereErrors()) {
delete generator;
return false;
}
const Id activeDiagram = mMainWindowInterface->activeDiagram();
const QString generatedCode = utils::InFile::readAll(generatedSrcPath);
if (!generatedCode.isEmpty()) {
mTextManager->showInTextEditor(path, generatorName(), language());
}
if (!openTab) {
mMainWindowInterface->activateItemOrDiagram(activeDiagram);
}
delete generator;
return true;
}
void RobotsGeneratorPluginBase::regenerateCode(const qReal::Id &diagram
, const QFileInfo &oldFileInfo
, const QFileInfo &newFileInfo)
{
if (!oldFileInfo.completeSuffix().compare(language().extension)) {
mCodePath.remove(diagram, oldFileInfo);
mCodePath.insert(diagram, newFileInfo);
regenerateExtraFiles(newFileInfo);
}
}
void RobotsGeneratorPluginBase::addNewCode(const Id &diagram, const QFileInfo &fileInfo)
{
mCodePath.insert(diagram, fileInfo);
}
void RobotsGeneratorPluginBase::removeDiagram(const qReal::Id &diagram)
{
mCodePath.remove(diagram);
}
void RobotsGeneratorPluginBase::removeCode(const QFileInfo &fileInfo)
{
const Id &diagram = mCodePath.key(fileInfo);
mCodePath.remove(diagram, fileInfo);
}
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/seq_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file workarounds/seq_workarounds.C
/// @brief Workarounds for the SEQ logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <generic/memory/lib/utils/scom.H>
#include <lib/workarounds/seq_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace seq
{
///
/// @brief ODT Config workaround
/// For Nimbus DD1, ODT2 and ODT3 bits are swapped in each of the PHY config registers
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed.
///
fapi2::ReturnCode odt_config( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
// skip the workaroud if attribute is not set
if (! mss::chip_ec_feature_mss_odt_config(i_target) )
{
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_INF("Running ODT Config workaround on %s", mss::c_str(i_target));
std::vector<fapi2::buffer<uint64_t>> l_read;
static const std::vector<uint64_t> ODT_REGS =
{
MCA_DDRPHY_SEQ_ODT_RD_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_RD_CONFIG1_P0,
MCA_DDRPHY_SEQ_ODT_WR_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_WR_CONFIG1_P0
};
FAPI_TRY(mss::scom_suckah(i_target, ODT_REGS, l_read));
for (auto& l_data : l_read)
{
// Note these bit positions are the same in RD_CONFIG* and WR_CONFIG*
constexpr uint64_t EVEN_RANK_ODT2 = 50;
constexpr uint64_t EVEN_RANK_ODT3 = 51;
constexpr uint64_t ODD_RANK_ODT2 = 58;
constexpr uint64_t ODD_RANK_ODT3 = 59;
bool l_odt2 = 0;
bool l_odt3 = 0;
// swap even rank ODT2 and ODT3
l_odt2 = l_data.getBit<EVEN_RANK_ODT2>();
l_odt3 = l_data.getBit<EVEN_RANK_ODT3>();
l_data.writeBit<EVEN_RANK_ODT2>(l_odt3).writeBit<EVEN_RANK_ODT3>(l_odt2);
// swap odd rank ODT2 and ODT3
l_odt2 = l_data.getBit<ODD_RANK_ODT2>();
l_odt3 = l_data.getBit<ODD_RANK_ODT3>();
l_data.writeBit<ODD_RANK_ODT2>(l_odt3).writeBit<ODD_RANK_ODT3>(l_odt2);
}
FAPI_TRY(mss::scom_blastah(i_target, ODT_REGS, l_read));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace seq
} // close namespace workarounds
} // close namespace mss
<commit_msg>Updates dramint training structure<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/seq_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2017,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file workarounds/seq_workarounds.C
/// @brief Workarounds for the SEQ logic blocks
/// Workarounds are very device specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Louis Stermole <stermole@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <generic/memory/lib/utils/scom.H>
#include <lib/workarounds/seq_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace seq
{
///
/// @brief ODT Config workaround
/// For Nimbus DD1, ODT2 and ODT3 bits are swapped in each of the PHY config registers
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed.
///
fapi2::ReturnCode odt_config( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
// skip the workaroud if attribute is not set
if (! mss::chip_ec_feature_mss_odt_config(i_target) )
{
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_INF("Running ODT Config workaround on %s", mss::c_str(i_target));
std::vector<fapi2::buffer<uint64_t>> l_read;
static const std::vector<uint64_t> ODT_REGS =
{
MCA_DDRPHY_SEQ_ODT_RD_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_RD_CONFIG1_P0,
MCA_DDRPHY_SEQ_ODT_WR_CONFIG0_P0, MCA_DDRPHY_SEQ_ODT_WR_CONFIG1_P0
};
FAPI_TRY(mss::scom_suckah(i_target, ODT_REGS, l_read));
for (auto& l_data : l_read)
{
// Note these bit positions are the same in RD_CONFIG* and WR_CONFIG*
constexpr uint64_t EVEN_RANK_ODT2 = 50;
constexpr uint64_t EVEN_RANK_ODT3 = 51;
constexpr uint64_t ODD_RANK_ODT2 = 58;
constexpr uint64_t ODD_RANK_ODT3 = 59;
bool l_odt2 = 0;
bool l_odt3 = 0;
// swap even rank ODT2 and ODT3
l_odt2 = l_data.getBit<EVEN_RANK_ODT2>();
l_odt3 = l_data.getBit<EVEN_RANK_ODT3>();
l_data.writeBit<EVEN_RANK_ODT2>(l_odt3).writeBit<EVEN_RANK_ODT3>(l_odt2);
// swap odd rank ODT2 and ODT3
l_odt2 = l_data.getBit<ODD_RANK_ODT2>();
l_odt3 = l_data.getBit<ODD_RANK_ODT3>();
l_data.writeBit<ODD_RANK_ODT2>(l_odt3).writeBit<ODD_RANK_ODT3>(l_odt2);
}
FAPI_TRY(mss::scom_blastah(i_target, ODT_REGS, l_read));
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace seq
} // close namespace workarounds
} // close namespace mss
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: postuninstall.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2007-03-26 14:11:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma warning(push, 1) /* disable warnings within system headers */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#pragma warning(pop)
#include <malloc.h>
#ifdef UNICODE
#define _UNICODE
#define _tstring wstring
#else
#define _tstring string
#endif
#include <tchar.h>
#include <string>
#if defined(_WIN32_WINNT) && !defined(__MINGW32__)
#error YES
#endif
#include <io.h>
static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
std::_tstring result;
TCHAR szDummy[1] = TEXT("");
DWORD nChars = 0;
if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
{
DWORD nBytes = ++nChars * sizeof(TCHAR);
LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
ZeroMemory( buffer, nBytes );
MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
result = buffer;
}
return result;
}
static BOOL ExecuteCommand( LPCTSTR lpCommand, BOOL bSync )
{
BOOL fSuccess = FALSE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
fSuccess = CreateProcess(
NULL,
(LPTSTR)lpCommand,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi
);
if ( fSuccess )
{
if ( bSync )
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
return fSuccess;
}
extern "C" UINT __stdcall ExecutePostUninstallScript( MSIHANDLE handle )
{
TCHAR szValue[8192];
DWORD nValueSize = sizeof(szValue);
HKEY hKey;
std::_tstring sInstDir;
std::_tstring sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );
// MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK );
if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER, sProductKey.c_str(), &hKey ) )
{
if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
{
sInstDir = szValue;
}
RegCloseKey( hKey );
}
else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, sProductKey.c_str(), &hKey ) )
{
if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
{
sInstDir = szValue;
}
RegCloseKey( hKey );
}
else
return ERROR_SUCCESS;
std::_tstring sInfFile = sInstDir + TEXT("program\\postuninstall.inf");
std::_tstring sCommand = _T("RUNDLL32.EXE ");
// MessageBox( NULL, sInfFile.c_str(), "Titel", MB_OK );
if ( (LONG)GetVersion() < 0 )
sCommand += _T("setupx.dll");
else
sCommand += _T("setupapi.dll");
sCommand += _T(",InstallHinfSection PostUninstall 132 ");
sCommand += sInfFile;
if ( 0 == _taccess( sInfFile.c_str(), 2 ) )
ExecuteCommand( sCommand.c_str(), TRUE );
DeleteFile( sInfFile.c_str() );
return ERROR_SUCCESS;
}
<commit_msg>INTEGRATION: CWS obo12 (1.5.8); FILE MERGED 2007/05/10 13:18:08 obo 1.5.8.2: #i76713# _WIN32_WINDOWS = 0x0410 for Win98 2007/05/10 10:36:55 obo 1.5.8.1: #i76713# #error YES removed (Vista PSDK)<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: postuninstall.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 10:50:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define _WIN32_WINDOWS 0x0410
#pragma warning(push, 1) /* disable warnings within system headers */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#pragma warning(pop)
#include <malloc.h>
#ifdef UNICODE
#define _UNICODE
#define _tstring wstring
#else
#define _tstring string
#endif
#include <tchar.h>
#include <string>
#include <io.h>
static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
std::_tstring result;
TCHAR szDummy[1] = TEXT("");
DWORD nChars = 0;
if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
{
DWORD nBytes = ++nChars * sizeof(TCHAR);
LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
ZeroMemory( buffer, nBytes );
MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
result = buffer;
}
return result;
}
static BOOL ExecuteCommand( LPCTSTR lpCommand, BOOL bSync )
{
BOOL fSuccess = FALSE;
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
fSuccess = CreateProcess(
NULL,
(LPTSTR)lpCommand,
NULL,
NULL,
FALSE,
0,
NULL,
NULL,
&si,
&pi
);
if ( fSuccess )
{
if ( bSync )
WaitForSingleObject( pi.hProcess, INFINITE );
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
}
return fSuccess;
}
extern "C" UINT __stdcall ExecutePostUninstallScript( MSIHANDLE handle )
{
TCHAR szValue[8192];
DWORD nValueSize = sizeof(szValue);
HKEY hKey;
std::_tstring sInstDir;
std::_tstring sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );
// MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK );
if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER, sProductKey.c_str(), &hKey ) )
{
if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
{
sInstDir = szValue;
}
RegCloseKey( hKey );
}
else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE, sProductKey.c_str(), &hKey ) )
{
if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("INSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
{
sInstDir = szValue;
}
RegCloseKey( hKey );
}
else
return ERROR_SUCCESS;
std::_tstring sInfFile = sInstDir + TEXT("program\\postuninstall.inf");
std::_tstring sCommand = _T("RUNDLL32.EXE ");
// MessageBox( NULL, sInfFile.c_str(), "Titel", MB_OK );
if ( (LONG)GetVersion() < 0 )
sCommand += _T("setupx.dll");
else
sCommand += _T("setupapi.dll");
sCommand += _T(",InstallHinfSection PostUninstall 132 ");
sCommand += sInfFile;
if ( 0 == _taccess( sInfFile.c_str(), 2 ) )
ExecuteCommand( sCommand.c_str(), TRUE );
DeleteFile( sInfFile.c_str() );
return ERROR_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2004 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 "Xalan" 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) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "XercesDOMImplementationBridge.hpp"
#if XERCES_VERSION_MAJOR >= 2
#include <xercesc/dom/deprecated/DOM_DOMImplementation.hpp>
#else
#include <xercesc/dom/DOM_DOMImplementation.hpp>
#endif
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/XercesParserLiaison/XercesDOMException.hpp>
XALAN_CPP_NAMESPACE_BEGIN
XercesDOMImplementationBridge::XercesDOMImplementationBridge(DOM_DOMImplementationType& theXercesDOMImplementation) :
XalanDOMImplementation(),
m_xercesNode(theXercesDOMImplementation)
{
}
XercesDOMImplementationBridge::~XercesDOMImplementationBridge()
{
}
XercesDOMImplementationBridge::XercesDOMImplementationBridge(const XercesDOMImplementationBridge& theSource) :
XalanDOMImplementation(theSource),
m_xercesNode(theSource.m_xercesNode)
{
}
bool
XercesDOMImplementationBridge::hasFeature(
const XalanDOMString& feature,
const XalanDOMString& version)
{
return m_xercesNode.hasFeature(c_wstr(feature), c_wstr(version));
}
XalanDocumentType*
XercesDOMImplementationBridge::createDocumentType(
const XalanDOMString& qualifiedName,
const XalanDOMString& publicId,
const XalanDOMString& systemId)
{
// $$$ ToDo: Fix this!!!
throw XercesDOMException(XercesDOMException::NO_MODIFICATION_ALLOWED_ERR);
return 0;
}
XalanDocument*
XercesDOMImplementationBridge::createDocument(
const XalanDOMString& namespaceURI,
const XalanDOMString& qualifiedName,
const XalanDocumentType& doctype)
{
// $$$ ToDo: Fix this!!!
throw XercesDOMException(XercesDOMException::NO_MODIFICATION_ALLOWED_ERR);
return 0;
}
XALAN_CPP_NAMESPACE_END
<commit_msg>Commented out unused parameters and fixed exception code.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999-2004 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 "Xalan" 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) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#include "XercesDOMImplementationBridge.hpp"
#if XERCES_VERSION_MAJOR >= 2
#include <xercesc/dom/deprecated/DOM_DOMImplementation.hpp>
#else
#include <xercesc/dom/DOM_DOMImplementation.hpp>
#endif
#include <xalanc/PlatformSupport/DOMStringHelper.hpp>
#include <xalanc/XercesParserLiaison/XercesDOMException.hpp>
XALAN_CPP_NAMESPACE_BEGIN
XercesDOMImplementationBridge::XercesDOMImplementationBridge(DOM_DOMImplementationType& theXercesDOMImplementation) :
XalanDOMImplementation(),
m_xercesNode(theXercesDOMImplementation)
{
}
XercesDOMImplementationBridge::~XercesDOMImplementationBridge()
{
}
XercesDOMImplementationBridge::XercesDOMImplementationBridge(const XercesDOMImplementationBridge& theSource) :
XalanDOMImplementation(theSource),
m_xercesNode(theSource.m_xercesNode)
{
}
bool
XercesDOMImplementationBridge::hasFeature(
const XalanDOMString& feature,
const XalanDOMString& version)
{
return m_xercesNode.hasFeature(c_wstr(feature), c_wstr(version));
}
XalanDocumentType*
XercesDOMImplementationBridge::createDocumentType(
const XalanDOMString& /* qualifiedName */,
const XalanDOMString& /* publicId */,
const XalanDOMString& /* systemId */)
{
throw XercesDOMException(XercesDOMException::NOT_SUPPORTED_ERR);
return 0;
}
XalanDocument*
XercesDOMImplementationBridge::createDocument(
const XalanDOMString& /* namespaceURI */,
const XalanDOMString& /* qualifiedName */,
const XalanDocumentType& /* doctype */)
{
throw XercesDOMException(XercesDOMException::NOT_SUPPORTED_ERR);
return 0;
}
XALAN_CPP_NAMESPACE_END
<|endoftext|>
|
<commit_before>
#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/opencv.hpp>
#include <sensor_msgs/Image.h>
#include <dynamic_reconfigure/server.h>
#include <hanse_object_detection/ObjectDetectionConfig.h>
#include "blobs/blob.h"
#include "blobs/BlobResult.h"
#include <vector>
#include <hanse_msgs/Object.h>
class ObjectDetection {
public:
ObjectDetection(ros::NodeHandle nh) {
image_pub = nh.advertise<sensor_msgs::Image>("/image_object_detection", 1);
object_pub = nh.advertise<hanse_msgs::Object>("/object", 1);
init();
}
void init() {
}
void configCallback(hanse_object_detection::ObjectDetectionConfig &config, uint32_t level)
{
init();
}
void imageCB(const sensor_msgs::ImageConstPtr& visual_img_msg)
{
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(visual_img_msg, sensor_msgs::image_encodings::RGB8);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge excepion: %s",e.what());
return;
}
cv::Mat image_rgb = cv_ptr->image;
std::vector<cv::Mat> channels;
cv::split(image_rgb, channels);
cv::Mat gray = channels[0];
cv::Mat binary;
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY_INV | cv::THRESH_OTSU);
IplImage *thresh = new IplImage(binary);
cvDilate(thresh, thresh, NULL, 20);
cvErode(thresh, thresh, NULL, 20);
CBlobResult blobs(thresh, NULL, 0);
blobs.Filter(blobs, B_EXCLUDE, CBlobGetArea(), B_LESS, 100 );
// Get largest blob.
int maxArea = 0;
int maxBlob = -1;
for (int j = 0; j < blobs.GetNumBlobs(); j++) {
CBlob *blob = blobs.GetBlob(j);
if (blob->Area() > maxArea) {
maxArea = blob->Area();
maxBlob = j;
}
}
float size = 0;
float orientation = 0;
float x = 0;
float y = 0;
if (maxBlob >= 0) {
size = blobs.GetBlob(maxBlob)->Moment(0, 0);
// First order moments -> mean position
double m10 = blobs.GetBlob(maxBlob)->Moment(1, 0) / size;
double m01 = blobs.GetBlob(maxBlob)->Moment(0, 1) / size;
x = m10;
y = m01;
// Second order moments -> orientation
double mu11 = blobs.GetBlob(maxBlob)->Moment(1, 1) / size;
double mu20 = blobs.GetBlob(maxBlob)->Moment(2, 0) / size;
double mu02 = blobs.GetBlob(maxBlob)->Moment(0, 2) / size;
orientation = 0.5 * atan2( 2 * mu11 , ( mu20 - mu02 ) );
// Draw blob to gray image.
binary = binary.setTo(cv::Scalar(0));
blobs.GetBlob(maxBlob)->FillBlob(thresh, cvScalar(255), 0, 0);
}
CvMoments M;
cvMoments(thresh, &M, 1);
// Second order moments -> orientation
double mu11 = cvGetCentralMoment( &M, 1, 1 ) / size;
double mu20 = cvGetCentralMoment( &M, 2, 0 ) / size;
double mu02 = cvGetCentralMoment( &M, 0, 2 ) / size;
orientation = 0.5 * atan2( 2 * mu11 , ( mu20 - mu02 ) );
cv::line(binary, cv::Point(x, y),
cv::Point(x + cos(orientation)*200, y + sin(orientation)*200),
cv::Scalar(120), 4, CV_FILLED);
// Theta is now the rotation angle reletive to the x axis.
// We want it relative to the y axis -> 90° ccw
orientation -= CV_PI / 2;
if (orientation < -CV_PI) {
orientation += CV_PI;
}
if (orientation < -CV_PI/2) {
orientation += CV_PI;
} else if (orientation > CV_PI/2) {
orientation -= CV_PI;
}
size /= (binary.rows * binary.cols);
hanse_msgs::Object objMsg;
objMsg.header = visual_img_msg->header;
objMsg.size = size;
objMsg.x = x;
objMsg.y = y;
objMsg.orientation = orientation;
object_pub.publish(objMsg);
cv_bridge::CvImage out_msg;
out_msg.header = visual_img_msg->header;
out_msg.encoding = sensor_msgs::image_encodings::MONO8;
out_msg.image = binary;
image_pub.publish(out_msg.toImageMsg());
}
private:
ros::Publisher image_pub;
ros::Publisher object_pub;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "object_detection_node");
ros::NodeHandle nh("~");
std::string image_topic = "/camera/rgb/image_color";
nh.getParam("image_topic", image_topic);
ObjectDetection od(nh);
dynamic_reconfigure::Server<hanse_object_detection::ObjectDetectionConfig> server;
dynamic_reconfigure::Server<hanse_object_detection::ObjectDetectionConfig>::CallbackType f;
f = boost::bind(&ObjectDetection::configCallback, &od, _1, _2);
server.setCallback(f);
ros::Subscriber camSub =
nh.subscribe<sensor_msgs::Image>(image_topic, 1, boost::bind(&ObjectDetection::imageCB, &od, _1));
ros::spin();
}
<commit_msg>object detection dynamic reconfigure<commit_after>
#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/opencv.hpp>
#include <sensor_msgs/Image.h>
#include <dynamic_reconfigure/server.h>
#include <hanse_object_detection/ObjectDetectionConfig.h>
#include "blobs/blob.h"
#include "blobs/BlobResult.h"
#include <vector>
#include <hanse_msgs/Object.h>
typedef enum {R, G, B} Channel;
class ObjectDetection {
public:
ObjectDetection(ros::NodeHandle nh) {
image_pub = nh.advertise<sensor_msgs::Image>("/image_object_detection", 1);
object_pub = nh.advertise<hanse_msgs::Object>("/object", 1);
channel = R;
inverted = false;
}
void configCallback(hanse_object_detection::ObjectDetectionConfig &config, uint32_t level)
{
std::string channelStr = config.channel;
if (channelStr.compare("R")) {
channel = R;
} else if (channelStr.compare("G")) {
channel = G;
} else if (channelStr.compare("B")) {
channel = B;
}
inverted = config.inverted;
}
void imageCB(const sensor_msgs::ImageConstPtr& visual_img_msg)
{
cv_bridge::CvImagePtr cv_ptr;
try {
cv_ptr = cv_bridge::toCvCopy(visual_img_msg, sensor_msgs::image_encodings::RGB8);
} catch (cv_bridge::Exception& e) {
ROS_ERROR("cv_bridge excepion: %s",e.what());
return;
}
cv::Mat image_rgb = cv_ptr->image;
std::vector<cv::Mat> channels;
cv::split(image_rgb, channels);
cv::Mat gray;
switch (channel) {
case R:
gray = channels[0];
break;
case G:
gray = channels[1];
break;
case B:
gray = channels[2];
break;
}
cv::Mat binary;
if (inverted) {
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY_INV | cv::THRESH_OTSU);
} else {
cv::threshold(gray, binary, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);
}
IplImage *thresh = new IplImage(binary);
cvDilate(thresh, thresh, NULL, 5);
cvErode(thresh, thresh, NULL, 5);
CBlobResult blobs(thresh, NULL, 0);
blobs.Filter(blobs, B_EXCLUDE, CBlobGetArea(), B_LESS, 100 );
// Get largest blob.
int maxArea = 0;
int maxBlob = -1;
for (int j = 0; j < blobs.GetNumBlobs(); j++) {
CBlob *blob = blobs.GetBlob(j);
if (blob->Area() > maxArea) {
maxArea = blob->Area();
maxBlob = j;
}
}
float size = 0;
float orientation = 0;
float x = 0;
float y = 0;
if (maxBlob >= 0) {
size = blobs.GetBlob(maxBlob)->Moment(0, 0);
// First order moments -> mean position
double m10 = blobs.GetBlob(maxBlob)->Moment(1, 0) / size;
double m01 = blobs.GetBlob(maxBlob)->Moment(0, 1) / size;
x = m10;
y = m01;
// Second order moments -> orientation
double mu11 = blobs.GetBlob(maxBlob)->Moment(1, 1) / size;
double mu20 = blobs.GetBlob(maxBlob)->Moment(2, 0) / size;
double mu02 = blobs.GetBlob(maxBlob)->Moment(0, 2) / size;
orientation = 0.5 * atan2( 2 * mu11 , ( mu20 - mu02 ) );
// Draw blob to gray image.
binary = binary.setTo(cv::Scalar(0));
blobs.GetBlob(maxBlob)->FillBlob(thresh, cvScalar(255), 0, 0);
}
CvMoments M;
cvMoments(thresh, &M, 1);
// Second order moments -> orientation
double mu11 = cvGetCentralMoment( &M, 1, 1 ) / size;
double mu20 = cvGetCentralMoment( &M, 2, 0 ) / size;
double mu02 = cvGetCentralMoment( &M, 0, 2 ) / size;
orientation = 0.5 * atan2( 2 * mu11 , ( mu20 - mu02 ) );
cv::line(binary, cv::Point(x, y),
cv::Point(x + cos(orientation)*200, y + sin(orientation)*200),
cv::Scalar(120), 4, CV_FILLED);
// Theta is now the rotation angle reletive to the x axis.
// We want it relative to the y axis -> 90° ccw
orientation -= CV_PI / 2;
if (orientation < -CV_PI) {
orientation += CV_PI;
}
if (orientation < -CV_PI/2) {
orientation += CV_PI;
} else if (orientation > CV_PI/2) {
orientation -= CV_PI;
}
size /= (binary.rows * binary.cols);
hanse_msgs::Object objMsg;
objMsg.header = visual_img_msg->header;
objMsg.size = size;
objMsg.x = x;
objMsg.y = y;
objMsg.orientation = orientation;
object_pub.publish(objMsg);
cv_bridge::CvImage out_msg;
out_msg.header = visual_img_msg->header;
out_msg.encoding = sensor_msgs::image_encodings::MONO8;
out_msg.image = binary;
image_pub.publish(out_msg.toImageMsg());
}
private:
ros::Publisher image_pub;
ros::Publisher object_pub;
Channel channel;
bool inverted;
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "object_detection_node");
ros::NodeHandle nh("~");
std::string image_topic = "/camera/rgb/image_color";
nh.getParam("image_topic", image_topic);
ObjectDetection od(nh);
dynamic_reconfigure::Server<hanse_object_detection::ObjectDetectionConfig> server;
dynamic_reconfigure::Server<hanse_object_detection::ObjectDetectionConfig>::CallbackType f;
f = boost::bind(&ObjectDetection::configCallback, &od, _1, _2);
server.setCallback(f);
ros::Subscriber camSub =
nh.subscribe<sensor_msgs::Image>(image_topic, 1, boost::bind(&ObjectDetection::imageCB, &od, _1));
ros::spin();
}
<|endoftext|>
|
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file process_model_interface.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__MODEL__PROCESS__PROCESS_MODEL_INTERFACE_HPP
#define FL__MODEL__PROCESS__PROCESS_MODEL_INTERFACE_HPP
#include <fl/util/traits.hpp>
namespace fl
{
/**
* \interface ProcessModelInterface
* \ingroup process_models
*
* \brief This reprersents the common process model interface of the form
* \f$p(x\mid x_t, u_t, v_t)\f$
*
* \tparam State Type of the state variable \f$x_t\f$
* \tparam Noise Type of the noise term \f$v_t\f$
* \tparam Input Type of the control input \f$u_t\f$
*/
template <
typename State,
typename Noise,
typename Input = internal::Empty
>
class ProcessModelInterface
: public internal::ProcessModelType
{
public:
typedef internal::ProcessModelType ModelType;
public:
/**
* Sets the conditional arguments \f$x_t, u_t\f$ of \f$p(x\mid x_t, u_t)\f$
*
* \param delta_time Prediction duration \f$\Delta t\f$
* \param state Previous state \f$x_{t}\f$
* \param input Control input \f$u_t\f$
*
* Once the conditional have been set, may either sample from this model
* since it also represents a conditional distribution or you may map
* a SNV noise term \f$v_t\f$ onto the distribution using
* \c map_standard_variate(\f$v_t\f$) if implemented.
*/
virtual void condition(const double& delta_time,
const State& state,
const Input& input = Input()) { }
/**
* Predicts the state conditioned on the previous state and input.
*
* \param delta_time Prediction duration \f$\Delta t\f$
* \param state Previous state \f$x_{t}\f$
* \param noise Additive or non-Additive noise \f$v_t\f$
* \param input Control input \f$u_t\f$
*
* \return State \f$x_{t+1}\sim p(x\mid x_t, u_t)\f$
*/
/// \todo have a default argument for the input, a default function which
/// has to be implemented by the derived classes
virtual State predict_state(double delta_time,
const State& state,
const Noise& noise,
const Input& input) = 0;
/**
* \return \f$\dim(x_t)\f$, dimension of the state
*/
virtual constexpr int state_dimension() const = 0;
/**
* \return \f$\dim(v_t)\f$, dimension of the noise
*/
virtual constexpr int noise_dimension() const = 0;
/**
* \return \f$\dim(u_t)\f$, dimension of the control input
*/
virtual constexpr int input_dimension() const = 0;
};
template <
typename State_,
typename Input_,
typename Noise_,
int Id = 0
>
class StateTransitionFunction
{
public:
typedef State_ State;
typedef Input_ Input;
typedef Noise_ Noise;
virtual State state(const State& prev_state,
const Input& input,
const Noise& noise) const = 0;
/**
* \return Dimension of the state variable $\f$x\f$
*/
virtual int state_dimension() const = 0;
/**
* \return Dimension of the noise term \f$w\f$
*/
virtual int noise_dimension() const = 0;
/**
* \return Dimension of the input \f$u_t\f$
*/
virtual int input_dimension() const = 0;
/**
* \return Model id number
*
* In case of multiple sensors of the same kind, this function returns the
* id of the individual model.
*/
virtual int id() const { return Id; }
/**
* Sets the model id
*
* \param new_id Model's new ID
*/
virtual void id(int) { /* const ID */ }
};
}
#endif
<commit_msg>Moved StateTransitionFunction to the top as the main model. Removed template argument Input default value<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac (jan.issac@gmail.com)
* Copyright (c) 2014 Manuel Wuthrich (manuel.wuthrich@gmail.com)
*
* Max-Planck Institute for Intelligent Systems, AMD Lab
* University of Southern California, CLMC Lab
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file process_model_interface.hpp
* \date October 2014
* \author Jan Issac (jan.issac@gmail.com)
*/
#ifndef FL__MODEL__PROCESS__PROCESS_MODEL_INTERFACE_HPP
#define FL__MODEL__PROCESS__PROCESS_MODEL_INTERFACE_HPP
#include <fl/util/traits.hpp>
namespace fl
{
template <
typename State_,
typename Noise_,
typename Input_,
int Id = 0
>
class StateTransitionFunction
{
public:
typedef State_ State;
typedef Noise_ Noise;
typedef Input_ Input;
virtual State state(const State& prev_state,
const Noise& noise,
const Input& input) const = 0;
/**
* \return Dimension of the state variable $\f$x\f$
*/
virtual int state_dimension() const = 0;
/**
* \return Dimension of the noise term \f$w\f$
*/
virtual int noise_dimension() const = 0;
/**
* \return Dimension of the input \f$u_t\f$
*/
virtual int input_dimension() const = 0;
/**
* \return Model id number
*
* In case of multiple sensors of the same kind, this function returns the
* id of the individual model.
*/
virtual int id() const { return Id; }
/**
* Sets the model id
*
* \param new_id Model's new ID
*/
virtual void id(int) { /* const ID */ }
};
/**
* \interface ProcessModelInterface
* \ingroup process_models
*
* \brief This reprersents the common process model interface of the form
* \f$p(x\mid x_t, u_t, v_t)\f$
*
* \tparam State Type of the state variable \f$x_t\f$
* \tparam Noise Type of the noise term \f$v_t\f$
* \tparam Input Type of the control input \f$u_t\f$
*/
template <
typename State,
typename Noise,
typename Input
>
class ProcessModelInterface
: public internal::ProcessModelType
{
public:
typedef internal::ProcessModelType ModelType;
public:
/**
* Sets the conditional arguments \f$x_t, u_t\f$ of \f$p(x\mid x_t, u_t)\f$
*
* \param delta_time Prediction duration \f$\Delta t\f$
* \param state Previous state \f$x_{t}\f$
* \param input Control input \f$u_t\f$
*
* Once the conditional have been set, may either sample from this model
* since it also represents a conditional distribution or you may map
* a SNV noise term \f$v_t\f$ onto the distribution using
* \c map_standard_variate(\f$v_t\f$) if implemented.
*/
virtual void condition(const double& delta_time,
const State& state,
const Input& input = Input()) { }
/**
* Predicts the state conditioned on the previous state and input.
*
* \param delta_time Prediction duration \f$\Delta t\f$
* \param state Previous state \f$x_{t}\f$
* \param noise Additive or non-Additive noise \f$v_t\f$
* \param input Control input \f$u_t\f$
*
* \return State \f$x_{t+1}\sim p(x\mid x_t, u_t)\f$
*/
/// \todo have a default argument for the input, a default function which
/// has to be implemented by the derived classes
virtual State predict_state(double delta_time,
const State& state,
const Noise& noise,
const Input& input) = 0;
/**
* \return \f$\dim(x_t)\f$, dimension of the state
*/
virtual constexpr int state_dimension() const = 0;
/**
* \return \f$\dim(v_t)\f$, dimension of the noise
*/
virtual constexpr int noise_dimension() const = 0;
/**
* \return \f$\dim(u_t)\f$, dimension of the control input
*/
virtual constexpr int input_dimension() const = 0;
};
}
#endif
<|endoftext|>
|
<commit_before>#include<malloc.h>
#include<stdio.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100 // 存储空间初始分配量
#define STACKINCREMENT 10 // 存储空间分配增量
typedef int SElemType; // 定义栈元素类型
typedef int Status; // Status是函数的类型,其值是函数结果状态代码,如OK等
struct SqStack
{
SElemType *base; // 在栈构造之前和销毁之后,base的值为NULL
SElemType *top; // 栈顶指针
int stacksize; // 当前已分配的存储空间,以元素为单位
Status InitStack()
{
// 构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE
// 请补全代码
base=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType)));
if(base=NULL)return ERROR;
top=base+1;
stacksize=STACK_INIT_SIZE;
return OK;
}
Status Push(SElemType e)
{
// 在栈S中插入元素e为新的栈顶元素
// 请补全代码
if(top-base>=stacksize){
base=(SElemType *) realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElemType));
if(base==NULL){
return ERROR;
}
}else{
*top=e;
top++;
}
return OK;
}
Status Pop(SElemType &e)
{
// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
// 请补全代码
if( top-base<=1){
return ERROR;
}
e=*(--top);
return OK;
}
Status GetTop(SElemType &e)
{
// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
// 请补全代码
if( top-base<=1){
return ERROR;
}
e=*(top-1);
return OK;
}
int StackLength()
{
// 返回栈S的元素个数
// 请补全代码
return top-base-1;
}
Status StackTraverse()
{
// 从栈顶到栈底依次输出栈中的每个元素
SElemType *p = (SElemType *)malloc(sizeof(SElemType));
p = *top; //请填空
if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空
else
{
printf("The Stack is: ");
p--;
while(p-base>1) //请填空
{
printf("%d ", *p);
p--; //请填空
}
}
printf("\n");
return OK;
}
}; // 顺序栈
int main()
{
int a;
SqStack S;
SElemType x, e;
if(S.InitStack()) // 判断顺序表是否创建成功,请填空
{
printf("A Stack Has Created.\n");
}
while(1)
{
printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
scanf("%d",&a);
switch(a)
{
case 1: scanf("%d", &x);
if(S.Push(x)) printf("Push Error!\n"); // 判断Push是否合法,请填空
else printf("The Element %d is Successfully Pushed!\n", x);
break;
case 2: if(S.Pop(e)) printf("Pop Error!\n"); // 判断Pop是否合法,请填空
else printf("The Element %d is Successfully Poped!\n", e);
break;
case 3: if(S.top(e))printf("Get Top Error!\n"); // 判断Get Top是否合法,请填空
else printf("The Top Element is %d!\n", e);
break;
case 4: printf("The Length of the Stack is %d!\n",S.StackLength()); //请填空
break;
case 5: S.StackTraverse() //请填空
break;
case 0: return 1;
}
}
}<commit_msg>update uoj8583<commit_after>#include<malloc.h>
#include<stdio.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100 // 存储空间初始分配量
#define STACKINCREMENT 10 // 存储空间分配增量
typedef int SElemType; // 定义栈元素类型
typedef int Status; // Status是函数的类型,其值是函数结果状态代码,如OK等
struct SqStack
{
SElemType *base; // 在栈构造之前和销毁之后,base的值为NULL
SElemType *top; // 栈顶指针
int stacksize; // 当前已分配的存储空间,以元素为单位
Status InitStack()
{
// 构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE
// 请补全代码
base=(SElemType*) malloc(STACK_INIT_SIZE*(sizeof(SElemType)));
if(base=NULL)return ERROR;
top=base+1;
stacksize=STACK_INIT_SIZE;
return OK;
}
Status Push(SElemType e)
{
// 在栈S中插入元素e为新的栈顶元素
// 请补全代码
if(top-base>=stacksize){
base=(SElemType *) realloc(base,(stacksize+STACKINCREMENT)*sizeof(SElemType));
if(base==NULL){
return ERROR;
}
}else{
*top=e;
top++;
}
return OK;
}
Status Pop(SElemType &e)
{
// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
// 请补全代码
if( top-base<=1){
return ERROR;
}
e=*(--top);
return OK;
}
Status GetTop(SElemType &e)
{
// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR
// 请补全代码
if( top-base<=1){
return ERROR;
}
e=*(top-1);
return OK;
}
int StackLength()
{
// 返回栈S的元素个数
// 请补全代码
return top-base-1;
}
Status StackTraverse()
{
// 从栈顶到栈底依次输出栈中的每个元素
SElemType *p = (SElemType *)malloc(sizeof(SElemType));
p = *top; //请填空
if(StackLength() ==0 )printf("The Stack is Empty!"); //请填空
else
{
printf("The Stack is: ");
p--;
while(p-base>1) //请填空
{
printf("%d ", *p);
p--; //请填空
}
}
printf("\n");
return OK;
}
}; // 顺序栈
int main()
{
int a;
SqStack S;
SElemType x, e;
if(S.InitStack()) // 判断顺序表是否创建成功,请填空
{
printf("A Stack Has Created.\n");
}
while(1)
{
printf("1:Push \n2:Pop \n3:Get the Top \n4:Return the Length of the Stack\n5:Load the Stack\n0:Exit\nPlease choose:\n");
scanf("%d",&a);
switch(a)
{
case 1: scanf("%d", &x);
if(S.Push(x)) printf("Push Error!\n"); // 判断Push是否合法,请填空
else printf("The Element %d is Successfully Pushed!\n", x);
break;
case 2: if(S.Pop(e)) printf("Pop Error!\n"); // 判断Pop是否合法,请填空
else printf("The Element %d is Successfully Poped!\n", e);
break;
case 3: if(S.GetTop(e))printf("Get Top Error!\n"); // 判断Get Top是否合法,请填空
else printf("The Top Element is %d!\n", e);
break;
case 4: printf("The Length of the Stack is %d!\n",S.StackLength()); //请填空
break;
case 5: S.StackTraverse(); //请填空
break;
case 0: return 1;
}
}
}<|endoftext|>
|
<commit_before>#ifndef VECRAND_H
#define VECRAND_H
#ifdef VEC2D
#define NDIM 2
#else
#ifndef VEC3D
#define VEC3D
#endif
#define NDIM 3
#endif
#include <iostream>
#include <ctime>
#include <vector>
#include <cmath>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/normal_distribution.hpp>
#include "vec.hpp"
using namespace std;
#ifdef LONGFLOAT
typedef long double flt;
inline flt cbrt(flt n){return cbrtl(n);};
inline flt expm1(flt n){return expm1l(n);};
inline flt copysign(flt n, flt m){return copysignl(n,m);};
inline flt remainder(flt n, flt m){return remainderl(n,m);};
inline flt round(flt n){return roundl(n);};
#else
typedef double flt;
#endif
#ifdef VEC2D
typedef Vector2<flt> Vec;
#else
typedef Vector3<flt> Vec;
#endif
typedef Numvector<flt, 2> Pair;
typedef Nvector<Vec, 2> VecPair;
using namespace std;
const flt OVERNDIM = ((flt) 1.0)/NDIM;
inline Vector2<flt> vec(double x, double y){
return Vector2<flt>(x,y);
};
inline Vector3<flt> vec(double x, double y, double z){
return Vector3<flt>(x,y,z);
};
inline uint vecsize(){return sizeof(Vec);}
typedef boost::mt19937 engine;
typedef boost::normal_distribution<flt> normdistribution;
typedef boost::uniform_01<flt, flt> lindistribution;
typedef boost::variate_generator<engine&, normdistribution > normgenerator;
typedef boost::variate_generator<engine&, lindistribution > lingenerator;
flt rand01();
Vec randVec();
Vec randVecBoxed();
#ifdef VEC3D
Vec randVecSphere(flt radius=1);
#endif
unsigned int seed(unsigned int n);
unsigned int seed();
class gaussVec {
protected:
normdistribution distro;
normgenerator gauss;
public:
gaussVec(flt sigma);
void set(flt sigma){distro = normdistribution(0,sigma);};
#ifdef VEC2D
Vec generate(){return Vec(gauss(),gauss());};
#else
Vec generate(){return Vec(gauss(),gauss(),gauss());};
#endif
};
class bivariateGauss {
protected:
normdistribution distro;
normgenerator gauss;
flt x11;
flt x21;
flt x22;
public:
bivariateGauss(const flt s1=1, const flt s2=1, const flt corr=0);
void set(const flt s1, const flt s2, const flt corr);
Pair generate();
#ifdef VEC2D
Vec genVec(){return Vec(gauss(), gauss());};
#else
Vec genVec(){return Vec(gauss(), gauss(), gauss());};
#endif
VecPair genVecs();
};
long double toLD(double e);
double fromLD(long double e);
vector<long double> LDVector(vector<double> dists);
#endif
<commit_msg>Fixed function collision error on Mac OS X clang<commit_after>#ifndef VECRAND_H
#define VECRAND_H
#ifdef VEC2D
#define NDIM 2
#else
#ifndef VEC3D
#define VEC3D
#endif
#define NDIM 3
#endif
#include <iostream>
#include <ctime>
#include <vector>
#include <cmath>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/normal_distribution.hpp>
#include "vec.hpp"
using namespace std;
#ifdef LONGFLOAT
typedef long double flt;
// on MAC OS, g++ is short for clang, and they already define the following functions pretty much
// the same way I do
#ifndef __clang__
inline flt cbrt(flt n){return cbrtl(n);};
inline flt expm1(flt n){return expm1l(n);};
inline flt copysign(flt n, flt m){return copysignl(n,m);};
inline flt remainder(flt n, flt m){return remainderl(n,m);};
inline flt round(flt n){return roundl(n);};
#endif
#else
typedef double flt;
#endif
#ifdef VEC2D
typedef Vector2<flt> Vec;
#else
typedef Vector3<flt> Vec;
#endif
typedef Numvector<flt, 2> Pair;
typedef Nvector<Vec, 2> VecPair;
using namespace std;
const flt OVERNDIM = ((flt) 1.0)/NDIM;
inline Vector2<flt> vec(double x, double y){
return Vector2<flt>(x,y);
};
inline Vector3<flt> vec(double x, double y, double z){
return Vector3<flt>(x,y,z);
};
inline uint vecsize(){return sizeof(Vec);}
typedef boost::mt19937 engine;
typedef boost::normal_distribution<flt> normdistribution;
typedef boost::uniform_01<flt, flt> lindistribution;
typedef boost::variate_generator<engine&, normdistribution > normgenerator;
typedef boost::variate_generator<engine&, lindistribution > lingenerator;
flt rand01();
Vec randVec();
Vec randVecBoxed();
#ifdef VEC3D
Vec randVecSphere(flt radius=1);
#endif
unsigned int seed(unsigned int n);
unsigned int seed();
class gaussVec {
protected:
normdistribution distro;
normgenerator gauss;
public:
gaussVec(flt sigma);
void set(flt sigma){distro = normdistribution(0,sigma);};
#ifdef VEC2D
Vec generate(){return Vec(gauss(),gauss());};
#else
Vec generate(){return Vec(gauss(),gauss(),gauss());};
#endif
};
class bivariateGauss {
protected:
normdistribution distro;
normgenerator gauss;
flt x11;
flt x21;
flt x22;
public:
bivariateGauss(const flt s1=1, const flt s2=1, const flt corr=0);
void set(const flt s1, const flt s2, const flt corr);
Pair generate();
#ifdef VEC2D
Vec genVec(){return Vec(gauss(), gauss());};
#else
Vec genVec(){return Vec(gauss(), gauss(), gauss());};
#endif
VecPair genVecs();
};
long double toLD(double e);
double fromLD(long double e);
vector<long double> LDVector(vector<double> dists);
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-cgb"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "6b6dfda"
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Revert "Git commit 6b6dfda"<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-cgb"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "32a928e"
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|>
|
<commit_before>#include "version.hpp"
// Get the git version macro from the build system
#include "vg_git_version.hpp"
// Do the same for the build environment info
#include "vg_environment_version.hpp"
#include <iostream>
#include <sstream>
// If the VG_GIT_VERSION deosn't exist at all, define a placeholder
// This lets us be somewhat robust to undeterminable versions
#ifndef VG_GIT_VERSION
#define VG_GIT_VERSION "not-from-git"
#endif
// Define a way to quote macro values.
// See https://stackoverflow.com/a/196093
#define QUOTE(arg) #arg
// We need another level to get the macro's value and not its name.
#define STR(macro) QUOTE(macro)
// Work out the standard library version
#ifdef _LIBCPP_VERSION
#define VG_STANDARD_LIBRARY_VERSION ("libc++ " STR(_LIBCPP_VERSION))
#endif
#ifdef __GLIBCXX__
#define VG_STANDARD_LIBRARY_VERSION ("libstd++ " STR(__GLIBCXX__))
#endif
#ifndef VG_STANDARD_LIBRARY_VERSION
#define VG_STANDARD_LIBRARY_VERSION "unknown standard library"
#endif
namespace vg {
using namespace std;
// Define all the strings as the macros' values
const string Version::VERSION = VG_GIT_VERSION;
const string Version::COMPILER = VG_COMPILER_VERSION;
const string Version::STANDARD_LIBRARY = VG_STANDARD_LIBRARY_VERSION;
const string Version::OS = VG_OS;
const string Version::BUILD_USER = VG_BUILD_USER;
const string Version::BUILD_HOST = VG_BUILD_HOST;
// Keep the list of codenames.
// Add new codenames here
const unordered_map<string, string> Version::codenames = {
{"v1.8.0", "Vallata"},
{"v1.9.0", "Miglionico"},
{"v1.10.0", "Rionero"},
{"v1.11.0", "Cairano"},
{"v1.12.0", "Parolise"},
{"v1.12.1", "Parolise"},
{"v1.13.0", "Moschiano"},
{"v1.14.0", "Quadrelle"},
{"v1.15.0", "Tufo"},
{"v1.16.0", "Rotondi"},
{"v1.17.0", "Candida"},
{"v1.18.0", "Zungoli"},
{"v1.19.0", "Tramutola"},
{"v1.20.0", "Ginestra"},
{"v1.21.0", "Fanano"},
{"v1.22.0", "Rotella"},
{"v1.23.0", "Lavello"},
{"v1.24.0", "Montieri"},
{"v1.25.0", "Apice"},
{"v1.26.0", "Stornara"},
{"v1.26.1", "Stornara"},
{"v1.27.0", "Deliceto"},
{"v1.28.0", "Acquafredda"},
{"v1.29.0", "Sospiro"},
{"v1.30.0", "Carentino"},
{"v1.31.0", "Caffaraccia"},
{"v1.32.0", "Sedlo"},
{"v1.33.0", "Moscona"},
{"v1.34.0", "Arguello"},
{"v1.35.0", "Ghizzano"},
{"v1.36.0", "Cibottola"}
// Add more codenames here
};
string Version::get_version() {
return VERSION;
}
string Version::get_release() {
auto dash = VERSION.find('-');
if (dash == -1) {
// Pure tag versions have no dash
return VERSION;
} else {
// Otherwise it is tag-count-ghash and the tag describes the release
return VERSION.substr(0, dash);
}
}
string Version::get_codename() {
auto release = get_release();
auto found = codenames.find(release);
if (found == codenames.end()) {
// No known codename for this release.
// Return an empty string so we can just not show it.
return "";
} else {
// We have a known codename!
return found->second;
}
}
string Version::get_short() {
stringstream s;
s << VERSION;
auto codename = get_codename();
if (!codename.empty()) {
// Add the codename if we have one
s << " \"" << codename << "\"";
}
return s.str();
}
string Version::get_long() {
stringstream s;
s << "vg version " << get_short() << endl;
s << "Compiled with " << COMPILER << " on " << OS << endl;
s << "Linked against " << STANDARD_LIBRARY << endl;
s << "Built by " << BUILD_USER << "@" << BUILD_HOST;
return s.str();
}
}
<commit_msg>Add another patch release<commit_after>#include "version.hpp"
// Get the git version macro from the build system
#include "vg_git_version.hpp"
// Do the same for the build environment info
#include "vg_environment_version.hpp"
#include <iostream>
#include <sstream>
// If the VG_GIT_VERSION deosn't exist at all, define a placeholder
// This lets us be somewhat robust to undeterminable versions
#ifndef VG_GIT_VERSION
#define VG_GIT_VERSION "not-from-git"
#endif
// Define a way to quote macro values.
// See https://stackoverflow.com/a/196093
#define QUOTE(arg) #arg
// We need another level to get the macro's value and not its name.
#define STR(macro) QUOTE(macro)
// Work out the standard library version
#ifdef _LIBCPP_VERSION
#define VG_STANDARD_LIBRARY_VERSION ("libc++ " STR(_LIBCPP_VERSION))
#endif
#ifdef __GLIBCXX__
#define VG_STANDARD_LIBRARY_VERSION ("libstd++ " STR(__GLIBCXX__))
#endif
#ifndef VG_STANDARD_LIBRARY_VERSION
#define VG_STANDARD_LIBRARY_VERSION "unknown standard library"
#endif
namespace vg {
using namespace std;
// Define all the strings as the macros' values
const string Version::VERSION = VG_GIT_VERSION;
const string Version::COMPILER = VG_COMPILER_VERSION;
const string Version::STANDARD_LIBRARY = VG_STANDARD_LIBRARY_VERSION;
const string Version::OS = VG_OS;
const string Version::BUILD_USER = VG_BUILD_USER;
const string Version::BUILD_HOST = VG_BUILD_HOST;
// Keep the list of codenames.
// Add new codenames here
const unordered_map<string, string> Version::codenames = {
{"v1.8.0", "Vallata"},
{"v1.9.0", "Miglionico"},
{"v1.10.0", "Rionero"},
{"v1.11.0", "Cairano"},
{"v1.12.0", "Parolise"},
{"v1.12.1", "Parolise"},
{"v1.13.0", "Moschiano"},
{"v1.14.0", "Quadrelle"},
{"v1.15.0", "Tufo"},
{"v1.16.0", "Rotondi"},
{"v1.17.0", "Candida"},
{"v1.18.0", "Zungoli"},
{"v1.19.0", "Tramutola"},
{"v1.20.0", "Ginestra"},
{"v1.21.0", "Fanano"},
{"v1.22.0", "Rotella"},
{"v1.23.0", "Lavello"},
{"v1.24.0", "Montieri"},
{"v1.25.0", "Apice"},
{"v1.26.0", "Stornara"},
{"v1.26.1", "Stornara"},
{"v1.27.0", "Deliceto"},
{"v1.27.1", "Deliceto"},
{"v1.28.0", "Acquafredda"},
{"v1.29.0", "Sospiro"},
{"v1.30.0", "Carentino"},
{"v1.31.0", "Caffaraccia"},
{"v1.32.0", "Sedlo"},
{"v1.33.0", "Moscona"},
{"v1.34.0", "Arguello"},
{"v1.35.0", "Ghizzano"},
{"v1.36.0", "Cibottola"}
// Add more codenames here
};
string Version::get_version() {
return VERSION;
}
string Version::get_release() {
auto dash = VERSION.find('-');
if (dash == -1) {
// Pure tag versions have no dash
return VERSION;
} else {
// Otherwise it is tag-count-ghash and the tag describes the release
return VERSION.substr(0, dash);
}
}
string Version::get_codename() {
auto release = get_release();
auto found = codenames.find(release);
if (found == codenames.end()) {
// No known codename for this release.
// Return an empty string so we can just not show it.
return "";
} else {
// We have a known codename!
return found->second;
}
}
string Version::get_short() {
stringstream s;
s << VERSION;
auto codename = get_codename();
if (!codename.empty()) {
// Add the codename if we have one
s << " \"" << codename << "\"";
}
return s.str();
}
string Version::get_long() {
stringstream s;
s << "vg version " << get_short() << endl;
s << "Compiled with " << COMPILER << " on " << OS << endl;
s << "Linked against " << STANDARD_LIBRARY << endl;
s << "Built by " << BUILD_USER << "@" << BUILD_HOST;
return s.str();
}
}
<|endoftext|>
|
<commit_before>// -------------------------------------------------------------------------------------
// Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
// For email, run on linux (perl v5.8.5):
// perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
// -------------------------------------------------------------------------------------
// Functionally correct solution. works for small inputs, but needs more
// algorithmic optimization for large inputs
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <assert.h>
using namespace std;
typedef unsigned int Ways;
#define MODNUM (1000000007)
class HyperCuboid {
private:
const int nsteps; //the number of steps to be taken
vector<int> spos; //the starting position in the hypercube
vector<int> dims; //the dimensions of the hypercube
Ways *cache[2]; //stores prev and next values of steps over the hypercube
//cache alloc/dealloc methods
void allocateCache();
void freeCache();
//checking, reading, and writing to indexes
bool onBoard(const vector<int>& index);
inline Ways& position(const vector<int>& index, int prevOrNext);
inline void writeIndex(const vector<int>& index, Ways value, int prevOrNext);
inline Ways readIndex(const vector<int>& index, int prevOrNext);
//iterating over indices
vector<int> getStartIndex();
void getNextIndex(vector<int>& index, bool& exists); //simple scheme to iterate on all indices
public:
HyperCuboid(int steps, const vector<int>& start, const vector<int>& dims);
Ways computeWays();
};
HyperCuboid::HyperCuboid(int steps, const vector<int>& start, const vector<int>& d)
: nsteps(steps), spos(start), dims(d) {
cache[0] = cache[1] = NULL;
}
vector<int> HyperCuboid::getStartIndex() {
return vector<int>(dims.size(), 0);
}
void HyperCuboid::getNextIndex(vector<int>& index, bool& exists) {
for (int i=dims.size()-1; i>=0; i--) {
if (index[i] == dims[i] - 1) { //this index reached the end
index[i] = 0; //reset it
} else {
index[i] += 1;
break;
}
}
if (index == getStartIndex()) {
exists = false;
return;
}
}
void HyperCuboid::allocateCache() {
int cellsNeeded = 1;
for (const int& d : dims) cellsNeeded *= d;
cache[0] = new Ways[cellsNeeded];
cache[1] = new Ways[cellsNeeded];
//initialize cache, this is base step of recursion
//at steps=0, I can only go to one place, that is my current place
vector<int> index = getStartIndex();
bool exists = true;
while (exists) {
writeIndex(index, 1, 0);
writeIndex(index, 0, 1);
getNextIndex(index, exists);
}
}
void HyperCuboid::freeCache() {
delete [] cache[0];
delete [] cache[1];
}
bool HyperCuboid::onBoard(const vector<int>& index) {
for (int i=0; i<dims.size(); i++) {
if (index[i] < 0 || index[i] >= dims[i]) return false;
}
return true;
}
Ways& HyperCuboid::position(const vector<int>& index, int prevOrNext) {
int chunkSize = 1; //stores size of current chunk
for (int i = 0; i<dims.size(); i++) chunkSize *= dims[i];
int offset = 0;
for (int i = 0; i<index.size(); i++) {
chunkSize /= dims[i]; //adjust my chunkSize
offset += index[i] * chunkSize;
}
return cache[prevOrNext][offset];
}
Ways HyperCuboid::readIndex(const vector<int>& index, int prevOrNext) {
return position(index, prevOrNext);
}
void HyperCuboid::writeIndex(const vector<int>& index, Ways value, int prevOrNext) {
position(index, prevOrNext) = value;
}
Ways HyperCuboid::computeWays() {
allocateCache();
//take the required number of steps
int prev=0, next=1;
for (int s=0; s<nsteps; s++) {
vector<int> index = getStartIndex();
bool exists = true;
while (exists) {
Ways curWays = 0;
for (int i=0; i<index.size(); i++) {
vector<int> stepIndexPlus = index;
vector<int> stepIndexMinus = index;
stepIndexPlus[i] += 1;
stepIndexMinus[i] -= 1;
if (onBoard(stepIndexPlus)) {
curWays += readIndex(stepIndexPlus, prev);
}
if (onBoard(stepIndexMinus)) {
curWays += readIndex(stepIndexMinus, prev);
}
}
curWays %= ((Ways) MODNUM);
writeIndex(index, curWays, next);
getNextIndex(index, exists);
}
next = 1-next;
prev = 1-prev;
}
Ways ways = readIndex(spos, prev);
freeCache();
ways = ways % ((Ways) MODNUM);
return ways;
}
int main() {
int tc; std::cin >> tc;
for (int t=0; t<tc; t++) {
int n, m;
std::cin >> n >> m;
vector<int> dims, pos;
for (int i=0; i<n; i++) {
int p; std::cin >> p;
pos.push_back(p-1); //make this 0-indexed right here
}
for (int i=0; i<n; i++) {
int d; std::cin >> d;
dims.push_back(d);
}
HyperCuboid hc(m, pos, dims);
Ways ans = hc.computeWays();
std::cout << ans << std::endl;
}
}
<commit_msg>Removing old version.<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include <eosio/trace_api_plugin/trace.hpp>
#include <exception>
#include <functional>
#include <map>
namespace eosio { namespace trace_api_plugin {
using chain::transaction_id_type;
using chain::packed_transaction;
template <typename StoreProvider>
class chain_extraction_impl_type {
public:
/**
* Chain Extractor for capturing transaction traces, action traces, and block info.
* @param store provider of append_data_log & append_metadata_log
* @param except_handler called on exceptions, logging if any is left to the user
* @param shutdown called when this class determines application should shutdown because of fatal error
*/
chain_extraction_impl_type( StoreProvider& store, std::function<void(std::exception_ptr)> except_handler )
: store(store)
, except_handler(std::move(except_handler))
{}
/// connect to chain controller applied_transaction signal
void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::signed_transaction& strx ) {
on_applied_transaction( trace, strx );
}
/// connect to chain controller accepted_block signal
void signal_accepted_block( const chain::block_state_ptr& bsp ) {
on_accepted_block( bsp );
}
/// connect to chain controller irreversible_block signal
void signal_irreversible_block( const chain::block_state_ptr& bsp ) {
on_irreversible_block( bsp );
}
private:
static bool is_onblock(const chain::transaction_trace_ptr& p) {
if (p->action_traces.size() != 1)
return false;
const auto& act = p->action_traces[0].act;
if (act.account != eosio::chain::config::system_account_name || act.name != N(onblock) ||
act.authorization.size() != 1)
return false;
const auto& auth = act.authorization[0];
return auth.actor == eosio::chain::config::system_account_name &&
auth.permission == eosio::chain::config::active_name;
}
void on_applied_transaction(const chain::transaction_trace_ptr& p, const chain::signed_transaction& t) {
if (p->receipt) {
if( is_onblock( p )) {
onblock_trace.emplace( p );
} else if (p->failed_dtrx_trace) {
cached_traces[p->failed_dtrx_trace->id] = p;
} else {
cached_traces[p->id] = p;
}
}
}
void on_accepted_block(const chain::block_state_ptr& block_state) {
store_block_trace( block_state );
}
void on_irreversible_block( const chain::block_state_ptr& block_state ) {
store_lib( block_state );
}
void store_block_trace( const chain::block_state_ptr& block_state ) {
try {
block_trace_v0 bt = create_block_trace_v0( block_state );
std::vector<transaction_trace_v0>& traces = bt.transactions;
traces.reserve( block_state->block->transactions.size() + 1 );
if( onblock_trace )
traces.emplace_back( to_transaction_trace_v0( *onblock_trace ));
for( const auto& r : block_state->block->transactions ) {
transaction_id_type id;
if( r.trx.contains<transaction_id_type>()) {
id = r.trx.get<transaction_id_type>();
} else {
id = r.trx.get<packed_transaction>().id();
}
const auto it = cached_traces.find( id );
// could assert, go with best effort
if( it != cached_traces.end() ) {
traces.emplace_back( to_transaction_trace_v0( it->second ));
} else {
traces.emplace_back( transaction_trace_v0{ .id = id } );
}
}
cached_traces.clear();
onblock_trace.reset();
uint64_t offset = store.append_data_log( std::move( bt ));
store.append_metadata_log( block_entry_v0{.id = block_state->id, .number = block_state->block_num, .offset = offset} );
} catch( ... ) {
except_handler( std::current_exception() );
}
}
void store_lib( const chain::block_state_ptr& bsp ) {
try {
store.append_metadata_log( lib_entry_v0{ .lib = bsp->block_num } );
} catch( ... ) {
except_handler( std::current_exception() );
}
}
private:
StoreProvider& store;
std::function<void(std::exception_ptr)> except_handler;
std::map<transaction_id_type, chain::transaction_trace_ptr> cached_traces;
fc::optional<chain::transaction_trace_ptr> onblock_trace;
};
}}<commit_msg>Take by value<commit_after>#pragma once
#include <eosio/trace_api_plugin/trace.hpp>
#include <eosio/trace_api_plugin/extract_util.hpp>
#include <exception>
#include <functional>
#include <map>
namespace eosio { namespace trace_api_plugin {
using chain::transaction_id_type;
using chain::packed_transaction;
template <typename StoreProvider>
class chain_extraction_impl_type {
public:
/**
* Chain Extractor for capturing transaction traces, action traces, and block info.
* @param store provider of append_data_log & append_metadata_log
* @param except_handler called on exceptions, logging if any is left to the user
* @param shutdown called when this class determines application should shutdown because of fatal error
*/
chain_extraction_impl_type( StoreProvider store, std::function<void(std::exception_ptr)> except_handler )
: store(std::move(store))
, except_handler(std::move(except_handler))
{}
/// connect to chain controller applied_transaction signal
void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::signed_transaction& strx ) {
on_applied_transaction( trace, strx );
}
/// connect to chain controller accepted_block signal
void signal_accepted_block( const chain::block_state_ptr& bsp ) {
on_accepted_block( bsp );
}
/// connect to chain controller irreversible_block signal
void signal_irreversible_block( const chain::block_state_ptr& bsp ) {
on_irreversible_block( bsp );
}
private:
static bool is_onblock(const chain::transaction_trace_ptr& p) {
if (p->action_traces.size() != 1)
return false;
const auto& act = p->action_traces[0].act;
if (act.account != eosio::chain::config::system_account_name || act.name != N(onblock) ||
act.authorization.size() != 1)
return false;
const auto& auth = act.authorization[0];
return auth.actor == eosio::chain::config::system_account_name &&
auth.permission == eosio::chain::config::active_name;
}
void on_applied_transaction(const chain::transaction_trace_ptr& p, const chain::signed_transaction& t) {
if (p->receipt) {
if( is_onblock( p )) {
onblock_trace.emplace( p );
} else if (p->failed_dtrx_trace) {
cached_traces[p->failed_dtrx_trace->id] = p;
} else {
cached_traces[p->id] = p;
}
}
}
void on_accepted_block(const chain::block_state_ptr& block_state) {
store_block_trace( block_state );
}
void on_irreversible_block( const chain::block_state_ptr& block_state ) {
store_lib( block_state );
}
void store_block_trace( const chain::block_state_ptr& block_state ) {
try {
block_trace_v0 bt = create_block_trace_v0( block_state );
std::vector<transaction_trace_v0>& traces = bt.transactions;
traces.reserve( block_state->block->transactions.size() + 1 );
if( onblock_trace )
traces.emplace_back( to_transaction_trace_v0( *onblock_trace ));
for( const auto& r : block_state->block->transactions ) {
transaction_id_type id;
if( r.trx.contains<transaction_id_type>()) {
id = r.trx.get<transaction_id_type>();
} else {
id = r.trx.get<packed_transaction>().id();
}
const auto it = cached_traces.find( id );
// could assert, go with best effort
if( it != cached_traces.end() ) {
traces.emplace_back( to_transaction_trace_v0( it->second ));
} else {
traces.emplace_back( transaction_trace_v0{ .id = id } );
}
}
cached_traces.clear();
onblock_trace.reset();
uint64_t offset = store.append_data_log( std::move( bt ));
store.append_metadata_log( block_entry_v0{.id = block_state->id, .number = block_state->block_num, .offset = offset} );
} catch( ... ) {
except_handler( std::current_exception() );
}
}
void store_lib( const chain::block_state_ptr& bsp ) {
try {
store.append_metadata_log( lib_entry_v0{ .lib = bsp->block_num } );
} catch( ... ) {
except_handler( std::current_exception() );
}
}
private:
StoreProvider store;
std::function<void(std::exception_ptr)> except_handler;
std::map<transaction_id_type, chain::transaction_trace_ptr> cached_traces;
fc::optional<chain::transaction_trace_ptr> onblock_trace;
};
}}<|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/>.
*/
/**
* @author Lefteris <lefteris@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include "CommandLineInterface.h"
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
namespace po = boost::program_options;
namespace dev
{
namespace solidity
{
static void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
static inline bool argToStdout(po::variables_map const& _args, const char* _name)
{
return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}
static bool needStdout(po::variables_map const& _args)
{
return argToStdout(_args, "abi") || argToStdout(_args, "natspec-user") || argToStdout(_args, "natspec-dev") ||
argToStdout(_args, "asm") || argToStdout(_args, "opcodes") || argToStdout(_args, "binary");
}
static inline bool outputToFile(OutputType type)
{
return type == OutputType::FILE || type == OutputType::BOTH;
}
static inline bool outputToStdout(OutputType type)
{
return type == OutputType::STDOUT || type == OutputType::BOTH;
}
static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
std::string token;
_in >> token;
if (token == "stdout")
io_output = OutputType::STDOUT;
else if (token == "file")
io_output = OutputType::FILE;
else if (token == "both")
io_output = OutputType::BOTH;
else
throw boost::program_options::invalid_option_value(token);
return _in;
}
void CommandLineInterface::handleBytecode(string const& _argName,
string const& _title,
string const& _contract,
string const& _suffix)
{
if (m_args.count(_argName))
{
auto choice = m_args[_argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << _title << endl;
if (_suffix == "opcodes")
;
// TODO: Figure out why after moving to own class ostream operator does not work for vector of bytes
// cout << m_compiler.getBytecode(_contract) << endl;
else
cout << toHex(m_compiler.getBytecode(_contract)) << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + _suffix);
if (_suffix == "opcodes")
;
// TODO: Figure out why after moving to own class ostream operator does not work for vector of bytes
// outFile << m_compiler.getBytecode(_contract);
else
outFile << toHex(m_compiler.getBytecode(_contract));
outFile.close();
}
}
}
void CommandLineInterface::handleJson(DocumentationType _type,
string const& _contract)
{
std::string argName;
std::string suffix;
std::string title;
switch(_type)
{
case DocumentationType::ABI_INTERFACE:
argName = "abi";
suffix = ".abi";
title = "Contract ABI";
break;
case DocumentationType::NATSPEC_USER:
argName = "natspec-user";
suffix = ".docuser";
title = "User Documentation";
break;
case DocumentationType::NATSPEC_DEV:
argName = "natspec-dev";
suffix = ".docdev";
title = "Developer Documentation";
break;
default:
// should never happen
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
}
if (m_args.count(argName))
{
auto choice = m_args[argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << title << endl;
cout << m_compiler.getJsonDocumentation(_contract, _type);
}
if (outputToFile(choice))
{
ofstream outFile(_contract + suffix);
outFile << m_compiler.getJsonDocumentation(_contract, _type);
outFile.close();
}
}
}
bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n" \
"\tstdout: Print it to standard output\n" \
"\tfile: Print it to a file with same name\n" \
"\tboth: Print both to a file and the stdout\n"
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message and exit")
("version", "Show version and exit")
("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
("input-file", po::value<vector<string>>(), "input file")
("ast", po::value<OutputType>(),
"Request to output the AST of the contract. " OUTPUT_TYPE_STR)
("asm", po::value<OutputType>(),
"Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
("opcodes", po::value<OutputType>(),
"Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
("binary", po::value<OutputType>(),
"Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
("abi", po::value<OutputType>(),
"Request to output the contract's ABI interface. " OUTPUT_TYPE_STR)
("natspec-user", po::value<OutputType>(),
"Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
("natspec-dev", po::value<OutputType>(),
"Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR
// All positional options should be interpreted as input files
po::positional_options_description p;
p.add("input-file", -1);
// parse the compiler arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
}
catch (po::error const& exception)
{
cout << exception.what() << endl;
return false;
}
po::notify(m_args);
if (m_args.count("help"))
{
cout << desc;
return false;
}
if (m_args.count("version"))
{
version();
return false;
}
return true;
}
bool CommandLineInterface::processInput()
{
if (!m_args.count("input-file"))
{
string s;
while (!cin.eof())
{
getline(cin, s);
m_sourceCodes["<stdin>"].append(s);
}
}
else
for (string const& infile: m_args["input-file"].as<vector<string>>())
m_sourceCodes[infile] = asString(dev::contents(infile));
try
{
for (auto const& sourceCode: m_sourceCodes)
m_compiler.addSource(sourceCode.first, sourceCode.second);
// TODO: Perhaps we should not compile unless requested
m_compiler.compile(m_args["optimize"].as<bool>());
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
return false;
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
return false;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
return false;
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
return false;
}
catch (InternalCompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler);
return false;
}
catch (Exception const& exception)
{
cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
return false;
}
catch (...)
{
cerr << "Unknown exception during compilation." << endl;
return false;
}
return true;
}
void CommandLineInterface::actOnInput()
{
// do we need AST output?
if (m_args.count("ast"))
{
auto choice = m_args["ast"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Syntax trees:" << endl << endl;
for (auto const& sourceCode: m_sourceCodes)
{
cout << endl << "======= " << sourceCode.first << " =======" << endl;
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(cout);
}
}
if (outputToFile(choice))
{
for (auto const& sourceCode: m_sourceCodes)
{
boost::filesystem::path p(sourceCode.first);
ofstream outFile(p.stem().string() + ".ast");
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(outFile);
outFile.close();
}
}
}
vector<string> contracts = m_compiler.getContractNames();
for (string const& contract: contracts)
{
if (needStdout(m_args))
cout << endl << "======= " << contract << " =======" << endl;
// do we need EVM assembly?
if (m_args.count("asm"))
{
auto choice = m_args["asm"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "EVM assembly:" << endl;
m_compiler.streamAssembly(cout, contract);
}
if (outputToFile(choice))
{
ofstream outFile(contract + ".evm");
m_compiler.streamAssembly(outFile, contract);
outFile.close();
}
}
handleBytecode("opcodes", "Opcodes:", contract, ".opcodes");
handleBytecode("binary", "Binary:", contract, ".binary");
handleJson(DocumentationType::ABI_INTERFACE, contract);
handleJson(DocumentationType::NATSPEC_DEV, contract);
handleJson(DocumentationType::NATSPEC_USER, contract);
} // end of contracts iteration
}
}
}
<commit_msg>Explicitly calling dev::operator<<() on two occassions due to mixup with boost<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/>.
*/
/**
* @author Lefteris <lefteris@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include "CommandLineInterface.h"
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
namespace po = boost::program_options;
namespace dev
{
namespace solidity
{
static void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
static inline bool argToStdout(po::variables_map const& _args, const char* _name)
{
return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}
static bool needStdout(po::variables_map const& _args)
{
return argToStdout(_args, "abi") || argToStdout(_args, "natspec-user") || argToStdout(_args, "natspec-dev") ||
argToStdout(_args, "asm") || argToStdout(_args, "opcodes") || argToStdout(_args, "binary");
}
static inline bool outputToFile(OutputType type)
{
return type == OutputType::FILE || type == OutputType::BOTH;
}
static inline bool outputToStdout(OutputType type)
{
return type == OutputType::STDOUT || type == OutputType::BOTH;
}
static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
std::string token;
_in >> token;
if (token == "stdout")
io_output = OutputType::STDOUT;
else if (token == "file")
io_output = OutputType::FILE;
else if (token == "both")
io_output = OutputType::BOTH;
else
throw boost::program_options::invalid_option_value(token);
return _in;
}
void CommandLineInterface::handleBytecode(string const& _argName,
string const& _title,
string const& _contract,
string const& _suffix)
{
if (m_args.count(_argName))
{
auto choice = m_args[_argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << _title << endl;
if (_suffix == "opcodes")
{
// TODO: Figure out why the wrong operator << (from boost) is used here
dev::operator<<(cout, m_compiler.getBytecode(_contract));
cout << endl;
}
else
cout << toHex(m_compiler.getBytecode(_contract)) << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + _suffix);
if (_suffix == "opcodes")
// TODO: Figure out why the wrong operator << (from boost) is used here
dev::operator<<(outFile, m_compiler.getBytecode(_contract));
else
outFile << toHex(m_compiler.getBytecode(_contract));
outFile.close();
}
}
}
void CommandLineInterface::handleJson(DocumentationType _type,
string const& _contract)
{
std::string argName;
std::string suffix;
std::string title;
switch(_type)
{
case DocumentationType::ABI_INTERFACE:
argName = "abi";
suffix = ".abi";
title = "Contract ABI";
break;
case DocumentationType::NATSPEC_USER:
argName = "natspec-user";
suffix = ".docuser";
title = "User Documentation";
break;
case DocumentationType::NATSPEC_DEV:
argName = "natspec-dev";
suffix = ".docdev";
title = "Developer Documentation";
break;
default:
// should never happen
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
}
if (m_args.count(argName))
{
auto choice = m_args[argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << title << endl;
cout << m_compiler.getJsonDocumentation(_contract, _type);
}
if (outputToFile(choice))
{
ofstream outFile(_contract + suffix);
outFile << m_compiler.getJsonDocumentation(_contract, _type);
outFile.close();
}
}
}
bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n" \
"\tstdout: Print it to standard output\n" \
"\tfile: Print it to a file with same name\n" \
"\tboth: Print both to a file and the stdout\n"
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message and exit")
("version", "Show version and exit")
("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
("input-file", po::value<vector<string>>(), "input file")
("ast", po::value<OutputType>(),
"Request to output the AST of the contract. " OUTPUT_TYPE_STR)
("asm", po::value<OutputType>(),
"Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
("opcodes", po::value<OutputType>(),
"Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
("binary", po::value<OutputType>(),
"Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
("abi", po::value<OutputType>(),
"Request to output the contract's ABI interface. " OUTPUT_TYPE_STR)
("natspec-user", po::value<OutputType>(),
"Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
("natspec-dev", po::value<OutputType>(),
"Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR
// All positional options should be interpreted as input files
po::positional_options_description p;
p.add("input-file", -1);
// parse the compiler arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
}
catch (po::error const& exception)
{
cout << exception.what() << endl;
return false;
}
po::notify(m_args);
if (m_args.count("help"))
{
cout << desc;
return false;
}
if (m_args.count("version"))
{
version();
return false;
}
return true;
}
bool CommandLineInterface::processInput()
{
if (!m_args.count("input-file"))
{
string s;
while (!cin.eof())
{
getline(cin, s);
m_sourceCodes["<stdin>"].append(s);
}
}
else
for (string const& infile: m_args["input-file"].as<vector<string>>())
m_sourceCodes[infile] = asString(dev::contents(infile));
try
{
for (auto const& sourceCode: m_sourceCodes)
m_compiler.addSource(sourceCode.first, sourceCode.second);
// TODO: Perhaps we should not compile unless requested
m_compiler.compile(m_args["optimize"].as<bool>());
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
return false;
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
return false;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
return false;
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
return false;
}
catch (InternalCompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler);
return false;
}
catch (Exception const& exception)
{
cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
return false;
}
catch (...)
{
cerr << "Unknown exception during compilation." << endl;
return false;
}
return true;
}
void CommandLineInterface::actOnInput()
{
// do we need AST output?
if (m_args.count("ast"))
{
auto choice = m_args["ast"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Syntax trees:" << endl << endl;
for (auto const& sourceCode: m_sourceCodes)
{
cout << endl << "======= " << sourceCode.first << " =======" << endl;
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(cout);
}
}
if (outputToFile(choice))
{
for (auto const& sourceCode: m_sourceCodes)
{
boost::filesystem::path p(sourceCode.first);
ofstream outFile(p.stem().string() + ".ast");
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(outFile);
outFile.close();
}
}
}
vector<string> contracts = m_compiler.getContractNames();
for (string const& contract: contracts)
{
if (needStdout(m_args))
cout << endl << "======= " << contract << " =======" << endl;
// do we need EVM assembly?
if (m_args.count("asm"))
{
auto choice = m_args["asm"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "EVM assembly:" << endl;
m_compiler.streamAssembly(cout, contract);
}
if (outputToFile(choice))
{
ofstream outFile(contract + ".evm");
m_compiler.streamAssembly(outFile, contract);
outFile.close();
}
}
handleBytecode("opcodes", "Opcodes:", contract, ".opcodes");
handleBytecode("binary", "Binary:", contract, ".binary");
handleJson(DocumentationType::ABI_INTERFACE, contract);
handleJson(DocumentationType::NATSPEC_DEV, contract);
handleJson(DocumentationType::NATSPEC_USER, contract);
} // end of contracts iteration
}
}
}
<|endoftext|>
|
<commit_before>// Copyright 2014 the V8 project authors. 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 Google 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.
#include "test/cctest/trace-extension.h"
#include "src/sampler.h"
#include "test/cctest/cctest.h"
namespace v8 {
namespace internal {
const char* TraceExtension::kSource =
"native function trace();"
"native function js_trace();"
"native function js_entry_sp();"
"native function js_entry_sp_level2();";
v8::Handle<v8::FunctionTemplate> TraceExtension::GetNativeFunctionTemplate(
v8::Isolate* isolate, v8::Handle<v8::String> name) {
if (name->Equals(v8::String::NewFromUtf8(isolate, "trace"))) {
return v8::FunctionTemplate::New(isolate, TraceExtension::Trace);
} else if (name->Equals(v8::String::NewFromUtf8(isolate, "js_trace"))) {
return v8::FunctionTemplate::New(isolate, TraceExtension::JSTrace);
} else if (name->Equals(v8::String::NewFromUtf8(isolate, "js_entry_sp"))) {
return v8::FunctionTemplate::New(isolate, TraceExtension::JSEntrySP);
} else if (name->Equals(v8::String::NewFromUtf8(isolate,
"js_entry_sp_level2"))) {
return v8::FunctionTemplate::New(isolate, TraceExtension::JSEntrySPLevel2);
} else {
CHECK(false);
return v8::Handle<v8::FunctionTemplate>();
}
}
Address TraceExtension::GetFP(const v8::FunctionCallbackInfo<v8::Value>& args) {
// Convert frame pointer from encoding as smis in the arguments to a pointer.
CHECK_EQ(2, args.Length()); // Ignore second argument on 32-bit platform.
#if defined(V8_HOST_ARCH_32_BIT)
Address fp = *reinterpret_cast<Address*>(*args[0]);
#elif defined(V8_HOST_ARCH_64_BIT)
int64_t low_bits = *reinterpret_cast<uint64_t*>(*args[0]) >> 32;
int64_t high_bits = *reinterpret_cast<uint64_t*>(*args[1]);
Address fp = reinterpret_cast<Address>(high_bits | low_bits);
#else
#error Host architecture is neither 32-bit nor 64-bit.
#endif
printf("Trace: %p\n", fp);
return fp;
}
static struct {
TickSample* sample;
} trace_env = { NULL };
void TraceExtension::InitTraceEnv(TickSample* sample) {
trace_env.sample = sample;
}
void TraceExtension::DoTrace(Address fp) {
RegisterState regs;
regs.fp = fp;
// sp is only used to define stack high bound
regs.sp =
reinterpret_cast<Address>(trace_env.sample) - 10240;
trace_env.sample->Init(CcTest::i_isolate(), regs,
TickSample::kSkipCEntryFrame);
}
void TraceExtension::Trace(const v8::FunctionCallbackInfo<v8::Value>& args) {
DoTrace(GetFP(args));
}
// Hide c_entry_fp to emulate situation when sampling is done while
// pure JS code is being executed
static void DoTraceHideCEntryFPAddress(Address fp) {
v8::internal::Address saved_c_frame_fp =
*(CcTest::i_isolate()->c_entry_fp_address());
CHECK(saved_c_frame_fp);
*(CcTest::i_isolate()->c_entry_fp_address()) = 0;
i::TraceExtension::DoTrace(fp);
*(CcTest::i_isolate()->c_entry_fp_address()) = saved_c_frame_fp;
}
void TraceExtension::JSTrace(const v8::FunctionCallbackInfo<v8::Value>& args) {
DoTraceHideCEntryFPAddress(GetFP(args));
}
Address TraceExtension::GetJsEntrySp() {
CHECK_NE(NULL, CcTest::i_isolate()->thread_local_top());
return CcTest::i_isolate()->js_entry_sp();
}
void TraceExtension::JSEntrySP(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK_NE(0, GetJsEntrySp());
}
void TraceExtension::JSEntrySPLevel2(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
const Address js_entry_sp = GetJsEntrySp();
CHECK_NE(0, js_entry_sp);
CompileRun("js_entry_sp();");
CHECK_EQ(js_entry_sp, GetJsEntrySp());
}
} } // namespace v8::internal
<commit_msg>ensure trace extension works from optimized code when profiler is not enabled<commit_after>// Copyright 2014 the V8 project authors. 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 Google 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.
#include "test/cctest/trace-extension.h"
#include "src/sampler.h"
#include "src/vm-state-inl.h"
#include "test/cctest/cctest.h"
namespace v8 {
namespace internal {
const char* TraceExtension::kSource =
"native function trace();"
"native function js_trace();"
"native function js_entry_sp();"
"native function js_entry_sp_level2();";
v8::Handle<v8::FunctionTemplate> TraceExtension::GetNativeFunctionTemplate(
v8::Isolate* isolate, v8::Handle<v8::String> name) {
if (name->Equals(v8::String::NewFromUtf8(isolate, "trace"))) {
return v8::FunctionTemplate::New(isolate, TraceExtension::Trace);
} else if (name->Equals(v8::String::NewFromUtf8(isolate, "js_trace"))) {
return v8::FunctionTemplate::New(isolate, TraceExtension::JSTrace);
} else if (name->Equals(v8::String::NewFromUtf8(isolate, "js_entry_sp"))) {
return v8::FunctionTemplate::New(isolate, TraceExtension::JSEntrySP);
} else if (name->Equals(v8::String::NewFromUtf8(isolate,
"js_entry_sp_level2"))) {
return v8::FunctionTemplate::New(isolate, TraceExtension::JSEntrySPLevel2);
} else {
CHECK(false);
return v8::Handle<v8::FunctionTemplate>();
}
}
Address TraceExtension::GetFP(const v8::FunctionCallbackInfo<v8::Value>& args) {
// Convert frame pointer from encoding as smis in the arguments to a pointer.
CHECK_EQ(2, args.Length()); // Ignore second argument on 32-bit platform.
#if defined(V8_HOST_ARCH_32_BIT)
Address fp = *reinterpret_cast<Address*>(*args[0]);
#elif defined(V8_HOST_ARCH_64_BIT)
int64_t low_bits = *reinterpret_cast<uint64_t*>(*args[0]) >> 32;
int64_t high_bits = *reinterpret_cast<uint64_t*>(*args[1]);
Address fp = reinterpret_cast<Address>(high_bits | low_bits);
#else
#error Host architecture is neither 32-bit nor 64-bit.
#endif
printf("Trace: %p\n", fp);
return fp;
}
static struct {
TickSample* sample;
} trace_env = { NULL };
void TraceExtension::InitTraceEnv(TickSample* sample) {
trace_env.sample = sample;
}
void TraceExtension::DoTrace(Address fp) {
RegisterState regs;
regs.fp = fp;
// sp is only used to define stack high bound
regs.sp =
reinterpret_cast<Address>(trace_env.sample) - 10240;
trace_env.sample->Init(CcTest::i_isolate(), regs,
TickSample::kSkipCEntryFrame);
}
void TraceExtension::Trace(const v8::FunctionCallbackInfo<v8::Value>& args) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(args.GetIsolate());
i::VMState<EXTERNAL> state(isolate);
Address address = reinterpret_cast<Address>(
reinterpret_cast<intptr_t>(&TraceExtension::Trace));
i::ExternalCallbackScope call_scope(isolate, address);
DoTrace(GetFP(args));
}
// Hide c_entry_fp to emulate situation when sampling is done while
// pure JS code is being executed
static void DoTraceHideCEntryFPAddress(Address fp) {
v8::internal::Address saved_c_frame_fp =
*(CcTest::i_isolate()->c_entry_fp_address());
CHECK(saved_c_frame_fp);
*(CcTest::i_isolate()->c_entry_fp_address()) = 0;
i::TraceExtension::DoTrace(fp);
*(CcTest::i_isolate()->c_entry_fp_address()) = saved_c_frame_fp;
}
void TraceExtension::JSTrace(const v8::FunctionCallbackInfo<v8::Value>& args) {
i::Isolate* isolate = reinterpret_cast<i::Isolate*>(args.GetIsolate());
i::VMState<EXTERNAL> state(isolate);
Address address = reinterpret_cast<Address>(
reinterpret_cast<intptr_t>(&TraceExtension::JSTrace));
i::ExternalCallbackScope call_scope(isolate, address);
DoTraceHideCEntryFPAddress(GetFP(args));
}
Address TraceExtension::GetJsEntrySp() {
CHECK_NE(NULL, CcTest::i_isolate()->thread_local_top());
return CcTest::i_isolate()->js_entry_sp();
}
void TraceExtension::JSEntrySP(
const v8::FunctionCallbackInfo<v8::Value>& args) {
CHECK_NE(0, GetJsEntrySp());
}
void TraceExtension::JSEntrySPLevel2(
const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope scope(args.GetIsolate());
const Address js_entry_sp = GetJsEntrySp();
CHECK_NE(0, js_entry_sp);
CompileRun("js_entry_sp();");
CHECK_EQ(js_entry_sp, GetJsEntrySp());
}
} } // namespace v8::internal
<|endoftext|>
|
<commit_before>#include "handler_unittest.hpp"
#include "fake_sys_file.hpp"
#include <google/protobuf/message_lite.h>
#include <google/protobuf/text_format.h>
#include <algorithm>
#include <boost/endian/arithmetic.hpp>
#include <memory>
#include <string>
#include <vector>
#include "binaryblob.pb.h"
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::AtLeast;
using ::testing::ElementsAreArray;
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::StrEq;
using ::testing::StrNe;
using ::testing::UnorderedElementsAreArray;
using namespace std::string_literals;
using namespace binstore;
namespace blobs
{
class BinaryStoreBlobHandlerBasicTest : public BinaryStoreBlobHandlerTest
{
protected:
static inline std::string basicTestBaseId = "/test/"s;
static inline std::string basicTestBlobId = "/test/blob0"s;
static const std::vector<std::string> basicTestBaseIdList;
static inline std::string basicTestInvalidBlobId = "/invalid/blob0"s;
void addAllBaseIds()
{
for (size_t i = 0; i < basicTestBaseIdList.size(); ++i)
{
auto store = defaultMockStore(basicTestBaseIdList[i]);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
handler.addNewBinaryStore(std::move(store));
}
}
};
const std::vector<std::string>
BinaryStoreBlobHandlerBasicTest::basicTestBaseIdList = {
BinaryStoreBlobHandlerBasicTest::basicTestBaseId, "/another/"s,
"/null\0/"s};
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobZeroStoreFail)
{
// Cannot handle since there is no store. Shouldn't crash.
EXPECT_FALSE(handler.canHandleBlob(basicTestInvalidBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobChecksName)
{
auto store = defaultMockStore(basicTestBaseId);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
handler.addNewBinaryStore(std::move(store));
// Verify canHandleBlob checks and returns false on an invalid name.
EXPECT_FALSE(handler.canHandleBlob(basicTestInvalidBlobId));
// Verify canHandleBlob return true for a blob id that it can handle
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, GetBlobIdEqualsConcatenationsOfBaseIds)
{
addAllBaseIds();
// When there is no other blob id, ids are just base ids (might be
// re-ordered).
EXPECT_THAT(handler.getBlobIds(),
UnorderedElementsAreArray(basicTestBaseIdList));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobInvalidNames)
{
addAllBaseIds();
const std::vector<std::string> invalidNames = {
basicTestInvalidBlobId,
"/"s,
"//"s,
"/test"s, // Cannot handle the base path
"/test/"s,
"/test/this/blob"s, // Cannot handle nested path
};
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
EXPECT_TRUE(
std::none_of(invalidNames.cbegin(), invalidNames.cend(), canHandle));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobValidNames)
{
addAllBaseIds();
const std::vector<std::string> validNames = {
basicTestBlobId, "/test/test"s, "/test/xyz.abc"s,
"/another/blob"s, "/null\0/\0\0zer\0\0"s,
};
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
// Verify canHandleBlob can handle a valid blob under the path.
EXPECT_TRUE(std::all_of(validNames.cbegin(), validNames.cend(), canHandle));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, DeleteReturnsWhatStoreReturns)
{
auto store = defaultMockStore(basicTestBaseId);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
EXPECT_CALL(*store, deleteBlob(StrEq(basicTestBlobId)))
.WillOnce(Return(false))
.WillOnce(Return(true));
handler.addNewBinaryStore(std::move(store));
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
// Verify canHandleBlob return true for a blob id that it can handle
EXPECT_FALSE(canHandle(basicTestInvalidBlobId));
EXPECT_TRUE(canHandle(basicTestBlobId));
EXPECT_FALSE(handler.deleteBlob(basicTestInvalidBlobId));
EXPECT_FALSE(handler.deleteBlob(basicTestBlobId));
EXPECT_TRUE(handler.deleteBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, StaleDataIsClearedDuringCreation)
{
using namespace google::protobuf;
auto basicTestStaleBlobStr =
R"(blob_base_id: "/stale/"
blobs {
blob_id: "/stale/blob"
})";
// Create sysfile containing a valid but stale blob
const std::string staleBaseId = "/stale/"s;
const std::string staleBlobId = "/stale/blob"s;
binaryblobproto::BinaryBlobBase staleBlob;
EXPECT_TRUE(TextFormat::ParseFromString(basicTestStaleBlobStr, &staleBlob));
// Serialize to string stored in the fakeSysFile
auto staleBlobData = staleBlob.SerializeAsString();
boost::endian::little_uint64_t sizeLE = staleBlobData.size();
std::string commitData(reinterpret_cast<const char*>(sizeLE.data()),
sizeof(sizeLE));
commitData += staleBlobData;
std::vector<std::string> expectedIdList = {basicTestBaseId};
handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(commitData)));
EXPECT_FALSE(handler.canHandleBlob(staleBlobId));
EXPECT_EQ(handler.getBlobIds(), expectedIdList);
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CreatingFromEmptySysfile)
{
const std::string emptyData;
EXPECT_NO_THROW(handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(emptyData))));
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CreatingFromJunkData)
{
boost::endian::little_uint64_t tooLarge = 0xffffffffffffffffull;
const std::string junkDataWithLargeSize(
reinterpret_cast<const char*>(tooLarge.data()), sizeof(tooLarge));
EXPECT_GE(tooLarge, junkDataWithLargeSize.max_size());
EXPECT_NO_THROW(handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId,
std::make_unique<FakeSysFile>(junkDataWithLargeSize))));
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
} // namespace blobs
<commit_msg>test: use char arrays instead of strings<commit_after>#include "handler_unittest.hpp"
#include "fake_sys_file.hpp"
#include <google/protobuf/message_lite.h>
#include <google/protobuf/text_format.h>
#include <algorithm>
#include <boost/endian/arithmetic.hpp>
#include <memory>
#include <string>
#include <vector>
#include "binaryblob.pb.h"
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::AtLeast;
using ::testing::ElementsAreArray;
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::StrEq;
using ::testing::StrNe;
using ::testing::UnorderedElementsAreArray;
using namespace std::string_literals;
using namespace binstore;
namespace blobs
{
class BinaryStoreBlobHandlerBasicTest : public BinaryStoreBlobHandlerTest
{
protected:
static inline char basicTestBaseId[] = "/test/";
static inline char basicTestBlobId[] = "/test/blob0";
static const std::vector<std::string> basicTestBaseIdList;
static inline char basicTestInvalidBlobId[] = "/invalid/blob0";
void addAllBaseIds()
{
for (size_t i = 0; i < basicTestBaseIdList.size(); ++i)
{
auto store = defaultMockStore(basicTestBaseIdList[i]);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
handler.addNewBinaryStore(std::move(store));
}
}
};
const std::vector<std::string>
BinaryStoreBlobHandlerBasicTest::basicTestBaseIdList = {
BinaryStoreBlobHandlerBasicTest::basicTestBaseId, "/another/"s,
"/null\0/"s};
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobZeroStoreFail)
{
// Cannot handle since there is no store. Shouldn't crash.
EXPECT_FALSE(handler.canHandleBlob(basicTestInvalidBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobChecksName)
{
auto store = defaultMockStore(basicTestBaseId);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
handler.addNewBinaryStore(std::move(store));
// Verify canHandleBlob checks and returns false on an invalid name.
EXPECT_FALSE(handler.canHandleBlob(basicTestInvalidBlobId));
// Verify canHandleBlob return true for a blob id that it can handle
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, GetBlobIdEqualsConcatenationsOfBaseIds)
{
addAllBaseIds();
// When there is no other blob id, ids are just base ids (might be
// re-ordered).
EXPECT_THAT(handler.getBlobIds(),
UnorderedElementsAreArray(basicTestBaseIdList));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobInvalidNames)
{
addAllBaseIds();
const std::vector<std::string> invalidNames = {
basicTestInvalidBlobId,
"/"s,
"//"s,
"/test"s, // Cannot handle the base path
"/test/"s,
"/test/this/blob"s, // Cannot handle nested path
};
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
EXPECT_TRUE(
std::none_of(invalidNames.cbegin(), invalidNames.cend(), canHandle));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobValidNames)
{
addAllBaseIds();
const std::vector<std::string> validNames = {
basicTestBlobId, "/test/test"s, "/test/xyz.abc"s,
"/another/blob"s, "/null\0/\0\0zer\0\0"s,
};
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
// Verify canHandleBlob can handle a valid blob under the path.
EXPECT_TRUE(std::all_of(validNames.cbegin(), validNames.cend(), canHandle));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, DeleteReturnsWhatStoreReturns)
{
auto store = defaultMockStore(basicTestBaseId);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
EXPECT_CALL(*store, deleteBlob(StrEq(basicTestBlobId)))
.WillOnce(Return(false))
.WillOnce(Return(true));
handler.addNewBinaryStore(std::move(store));
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
// Verify canHandleBlob return true for a blob id that it can handle
EXPECT_FALSE(canHandle(basicTestInvalidBlobId));
EXPECT_TRUE(canHandle(basicTestBlobId));
EXPECT_FALSE(handler.deleteBlob(basicTestInvalidBlobId));
EXPECT_FALSE(handler.deleteBlob(basicTestBlobId));
EXPECT_TRUE(handler.deleteBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, StaleDataIsClearedDuringCreation)
{
using namespace google::protobuf;
auto basicTestStaleBlobStr =
R"(blob_base_id: "/stale/"
blobs {
blob_id: "/stale/blob"
})";
// Create sysfile containing a valid but stale blob
const std::string staleBaseId = "/stale/"s;
const std::string staleBlobId = "/stale/blob"s;
binaryblobproto::BinaryBlobBase staleBlob;
EXPECT_TRUE(TextFormat::ParseFromString(basicTestStaleBlobStr, &staleBlob));
// Serialize to string stored in the fakeSysFile
auto staleBlobData = staleBlob.SerializeAsString();
boost::endian::little_uint64_t sizeLE = staleBlobData.size();
std::string commitData(reinterpret_cast<const char*>(sizeLE.data()),
sizeof(sizeLE));
commitData += staleBlobData;
std::vector<std::string> expectedIdList = {basicTestBaseId};
handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(commitData)));
EXPECT_FALSE(handler.canHandleBlob(staleBlobId));
EXPECT_EQ(handler.getBlobIds(), expectedIdList);
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CreatingFromEmptySysfile)
{
const std::string emptyData;
EXPECT_NO_THROW(handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(emptyData))));
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CreatingFromJunkData)
{
boost::endian::little_uint64_t tooLarge = 0xffffffffffffffffull;
const std::string junkDataWithLargeSize(
reinterpret_cast<const char*>(tooLarge.data()), sizeof(tooLarge));
EXPECT_GE(tooLarge, junkDataWithLargeSize.max_size());
EXPECT_NO_THROW(handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId,
std::make_unique<FakeSysFile>(junkDataWithLargeSize))));
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
} // namespace blobs
<|endoftext|>
|
<commit_before>// Micro Power Snitch code, including periodic radio packet transmissions.
// See http://jeelabs.org/2015/03/11/micro-power-snitch-part-4/
#include "sys.h"
#define chThdYield() // FIXME still used in rf69.h
#include "spi.h"
#include "rf69.h"
RF69<SpiDev0> rf;
static void sleep (int ticks) {
LPC_WKT->COUNT = ticks; // sleep time in 0.1 ms steps
SCB->SCR |= 1<<2; // enable SLEEPDEEP mode
__WFI();
SCB->SCR &= ~(1<<2); // disable SLEEPDEEP mode
}
int main () {
// enable wake-ups via low-power watchdog interrupts
LPC_SYSCON->SYSAHBCLKCTRL |= 1<<9; // SYSCTL_CLOCK_WKT
LPC_WKT->CTRL = 1<<0; // WKT_CTRL_CLKSEL
NVIC_EnableIRQ(WKT_IRQn);
// power-down setup (can't use deep power down, loses I/O pin statet)
LPC_SYSCON->STARTERP1 = 1<<15; // wake up from alarm/wake timer
LPC_PMU->DPDCTRL = (1<<2) | (1<<1); // LPOSCEN, no wakepad
LPC_PMU->PCON = 2; // use normal power-down mode
// disable all special pin functions
LPC_SWM->PINENABLE0 = ~0;
// make all SPI pins "0" outputs to prevent radio back-feeding
LPC_GPIO_PORT->DIR[0] |= 0b111110; // pio1..5 all outputs
LPC_GPIO_PORT->CLR[0] = 0b111100; // pio2..5 set to 0
LPC_GPIO_PORT->SET[0] = 0b000010; // pio1 set to 1
sleep(10000); // sleep 1 sec to let power supply rise further
LPC_GPIO_PORT->DIR[0] &= ~0b111100; // pio2..5 all inputs again
LPC_GPIO_PORT->B[0][1] = 0; // low, turns radio power on
sleep(100); // sleep 10 ms to let the radio start up
// SPI0 pin configuration
// lpc810: sck=3p3, ssel=4p2, miso=2p4, mosi=5p1
LPC_SWM->PINASSIGN[3] = 0x03FFFFFF; // sck - - -
LPC_SWM->PINASSIGN[4] = 0xFF040205; // - nss miso mosi
// initialise the radio and put it into idle mode asap
rf.init(61, 42, 8683); // node 61, group 42, 868.3 MHz
rf.sleep();
// configure the radio a bit more
// rf.encrypt("mysecret");
rf.txPower(0); // 0 = min .. 31 = max
sleep(10000); // sleep 1 sec before entering the main loop
while (true) {
// send out one packet and go back to sleep
rf.send(0, "xyz", 3);
rf.sleep();
sleep(10000); // sleep 1 sec
}
}
extern "C" void WKT_IRQHandler () {
LPC_WKT->CTRL = LPC_WKT->CTRL; // clear the alarm interrupt
// LPC_WKT->CTRL |= (1<<1) | (1<<2); // clear alarm
}
<commit_msg>comment tweaks<commit_after>// Micro Power Snitch code, including periodic radio packet transmissions.
// See http://jeelabs.org/2015/03/11/micro-power-snitch-part-4/
#include "sys.h"
#define chThdYield() // FIXME still used in rf69.h
#include "spi.h"
#include "rf69.h"
RF69<SpiDev0> rf;
static void sleep (int ticks) {
LPC_WKT->COUNT = ticks; // sleep time in 0.1 ms steps
SCB->SCR |= 1<<2; // enable SLEEPDEEP mode
__WFI();
SCB->SCR &= ~(1<<2); // disable SLEEPDEEP mode
}
int main () {
// enable wake-ups via low-power watchdog interrupts
LPC_SYSCON->SYSAHBCLKCTRL |= 1<<9; // SYSCTL_CLOCK_WKT
LPC_WKT->CTRL = 1<<0; // WKT_CTRL_CLKSEL
NVIC_EnableIRQ(WKT_IRQn);
// power-down setup (can't use deep power down, loses I/O pin state)
LPC_SYSCON->STARTERP1 = 1<<15; // wake up from alarm/wake timer
LPC_PMU->DPDCTRL = (1<<2) | (1<<1); // LPOSCEN, no wakepad
LPC_PMU->PCON = 2; // use normal power-down mode
// disable all special pin functions
LPC_SWM->PINENABLE0 = ~0;
// make all SPI pins "0" outputs to prevent radio back-feeding
LPC_GPIO_PORT->DIR[0] |= 0b111110; // pio1..5 all outputs
LPC_GPIO_PORT->CLR[0] = 0b111100; // pio2..5 set to 0
LPC_GPIO_PORT->SET[0] = 0b000010; // pio1 set to 1
sleep(10000); // sleep 1 sec to let power supply rise further
LPC_GPIO_PORT->DIR[0] &= ~0b111100; // pio2..5 all inputs again
LPC_GPIO_PORT->B[0][1] = 0; // low, turns radio power on
sleep(100); // sleep 10 ms to let the radio start up
// SPI0 pin configuration
// lpc810: sck=3p3, ssel=4p2, miso=2p4, mosi=5p1
LPC_SWM->PINASSIGN[3] = 0x03FFFFFF; // sck - - -
LPC_SWM->PINASSIGN[4] = 0xFF040205; // - nss miso mosi
// initialise the radio and put it into idle mode asap
rf.init(61, 42, 8683); // node 61, group 42, 868.3 MHz
rf.sleep();
// configure the radio a bit more
// rf.encrypt("mysecret");
rf.txPower(0); // 0 = min .. 31 = max
sleep(10000); // sleep 1 sec before entering the main loop
while (true) {
// send out one packet and go back to sleep
rf.send(0, "xyz", 3);
rf.sleep();
sleep(10000); // sleep 1 sec
}
}
extern "C" void WKT_IRQHandler () {
LPC_WKT->CTRL = LPC_WKT->CTRL; // clear the alarm interrupt
// LPC_WKT->CTRL |= (1<<1) | (1<<2); // clear alarm
}
<|endoftext|>
|
<commit_before>void CreateCalibPars_Miscalibrated(){
// Create TOF Calibration Object for miscalibrated detector
// and write it on CDB
AliTOFGeometry *geom = new AliTOFGeometryV5();
AliTOFcalib *tofcalib = new AliTOFcalib(geom);
AliTOFCal *tofCal= new AliTOFCal(geom);
tofCal->CreateArray();
// Input data for decalibration
TFile f("$ALICE_ROOT/TOF/data/spectrum.root","READ");
TH1F *hTimeToTFit= (TH1F*)f.Get("TimeToTFit");
TF1 *fit=hTimeToTFit->GetFunction("poly5");
// Slewing parameters (same for all channels)
Float_t par[6] = {0.,0.,0.,0.,0.,0.};
for(Int_t i =0;i<6;i++){
par[i]=fit->GetParameter(i);
// cout << " Slewing parameters=" << par[i] << endl;
}
// Global time offset (randomly gen, gaussian with mean = 0.3, sig=0.08 ns)
Float_t delay=0.;
Float_t meanDelay=0.3;
Float_t sigmaDelay=0.08;
// ToT spectrum
TH1F *hToT= (TH1F*)f.Get("ToT");
// Fill the Sim calibration object
TRandom *rnd = new TRandom(4357);
for (Int_t ipad = 0 ; ipad<tofCal->NPads(); ipad++){
AliTOFChannel *calChannel = tofCal->GetChannel(ipad);
calChannel->SetSlewPar(par);
delay=rnd->Gaus(meanDelay,sigmaDelay);
// cout << " delay=" << delay << endl;
calChannel->SetDelay(delay);
}
tofcalib->WriteSimParOnCDB("TOF/Calib",0,0,tofCal,hToT);
f.Close();
}
<commit_msg>Updates to fetch the restricted spectra in TOF/data/spectrum.root<commit_after>void CreateCalibPars_Miscalibrated(){
// Create TOF Calibration Object for miscalibrated detector
// and write it on CDB
AliTOFGeometry *geom = new AliTOFGeometryV5();
AliTOFcalib *tofcalib = new AliTOFcalib(geom);
AliTOFCal *tofCal= new AliTOFCal(geom);
tofCal->CreateArray();
// Input data for decalibration
TFile f("$ALICE_ROOT/TOF/data/spectrum.root","READ");
TH1F *hTimeToTFit= (TH1F*)f.Get("hTimeToTLim");
TF1 *fit=hTimeToTFit->GetFunction("pol5");
// Slewing parameters (same for all channels)
Float_t par[6] = {0.,0.,0.,0.,0.,0.};
for(Int_t i =0;i<6;i++){
par[i]=fit->GetParameter(i);
cout << " Slewing parameters=" << par[i] << endl;
}
// Global time offset (randomly gen, gaussian with mean = 0.3, sig=0.08 ns)
Float_t delay=0.;
Float_t meanDelay=0.3;
Float_t sigmaDelay=0.08;
// ToT spectrum
TH1F *hToT= (TH1F*)f.Get("hToTLim");
// Fill the Sim calibration object
TRandom *rnd = new TRandom(4357);
for (Int_t ipad = 0 ; ipad<tofCal->NPads(); ipad++){
AliTOFChannel *calChannel = tofCal->GetChannel(ipad);
calChannel->SetSlewPar(par);
delay=rnd->Gaus(meanDelay,sigmaDelay);
calChannel->SetDelay(delay);
}
tofcalib->WriteSimParOnCDB("TOF/Calib",0,0,tofCal,hToT);
f.Close();
}
<|endoftext|>
|
<commit_before>// $Id: atomContainer.C,v 1.10 2001/07/15 16:12:42 oliver Exp $
#include <BALL/KERNEL/atomContainer.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/global.h>
#include <BALL/KERNEL/molecule.h>
using namespace std;
namespace BALL
{
AtomContainer::AtomContainer()
throw()
: Composite(),
PropertyManager(),
name_(BALL_ATOMCONTAINER_DEFAULT_NAME)
{
}
AtomContainer::AtomContainer(const AtomContainer& atom_container, bool deep)
throw()
: Composite(),
PropertyManager(),
name_()
{
set(atom_container, deep);
}
AtomContainer::AtomContainer(const String& name)
throw()
: Composite(),
PropertyManager(),
name_(name)
{
}
AtomContainer::~AtomContainer()
throw()
{
destroy();
}
void AtomContainer::clear()
throw()
{
Composite::clear();
PropertyManager::clear();
name_ = BALL_ATOMCONTAINER_DEFAULT_NAME;
}
void AtomContainer::destroy()
throw()
{
Composite::destroy();
PropertyManager::destroy();
name_ = BALL_ATOMCONTAINER_DEFAULT_NAME;
}
void AtomContainer::persistentWrite(PersistenceManager& pm, const char* name) const
throw(Exception::GeneralException)
{
pm.writeObjectHeader(this, name);
Composite::persistentWrite(pm);
pm.writeStorableObject(*(PropertyManager*)this, "PropertyManager");
pm.writePrimitive(name_, "name_");
pm.writeObjectTrailer(name);
}
void AtomContainer::persistentRead(PersistenceManager& pm)
throw(Exception::GeneralException)
{
pm.checkObjectHeader(RTTI::getStreamName<Composite>());
Composite::persistentRead(pm);
pm.checkObjectTrailer(0);
pm.readStorableObject(*(PropertyManager*)this, "PropertyManager");
pm.readPrimitive(name_, "name_");
}
void AtomContainer::set(const AtomContainer& atom_container, bool deep)
throw()
{
bool clone_them = clone_bonds;
clone_bonds = false;
Composite::set(atom_container, deep);
PropertyManager::set(atom_container);
name_ = atom_container.name_;
// clone the bonds only of we are the outmost set method
// involved!
if (clone_them && deep)
{
BALL::cloneBonds(atom_container, *this);
}
clone_bonds = clone_them;
}
const AtomContainer& AtomContainer::operator = (const AtomContainer& atom_container)
throw()
{
set(atom_container);
return *this;
}
void AtomContainer::get(AtomContainer& atom_container, bool deep) const
throw()
{
atom_container.set(*this, deep);
}
void AtomContainer::swap(AtomContainer& atom_container)
throw()
{
Composite::swap(atom_container);
PropertyManager::swap(atom_container);
name_.swap(atom_container.name_);
}
void AtomContainer::setName(const String& name)
throw()
{
name_ = name;
}
const String& AtomContainer::getName() const
throw()
{
return name_;
}
/* BAUSTELLE - remove?
Molecule* AtomContainer::getMolecule()
throw()
{
for (Composite::AncestorIterator ancestor_it = beginAncestor();
!ancestor_it.isEnd(); ++ancestor_it)
{
if (RTTI::isKindOf<Molecule>(*ancestor_it) == true)
{
return (Molecule *)&*ancestor_it;
}
}
return 0;
}
const Molecule* AtomContainer::getMolecule() const
throw()
{
return ((AtomContainer *)this)->getMolecule();
}
*/
AtomContainer* AtomContainer::getSuperAtomContainer()
throw()
{
for (Composite::AncestorIterator ancestor_it = beginAncestor();
!ancestor_it.isEnd(); ++ancestor_it)
{
if (RTTI::isKindOf<AtomContainer>(*ancestor_it) == true)
{
return (AtomContainer *)&*ancestor_it;
}
}
return 0;
}
const AtomContainer* AtomContainer::getSuperAtomContainer() const
throw()
{
return ((AtomContainer *)this)->getSuperAtomContainer();
}
AtomContainer* AtomContainer::getAtomContainer(Position position)
throw()
{
for (AtomContainerIterator atom_container_it = ++beginAtomContainer();
!atom_container_it.isEnd(); ++atom_container_it)
{
if (position-- == 0)
{
return &(*atom_container_it);
}
}
return 0;
}
const AtomContainer* AtomContainer::getAtomContainer(Position position) const
throw()
{
return ((AtomContainer *)this)->getAtomContainer(position);
}
Atom* AtomContainer::getAtom(Position position)
throw()
{
for (AtomIterator atom_it = beginAtom(); !atom_it.isEnd(); ++atom_it)
{
if (position-- == 0)
{
return &(*atom_it);
}
}
return 0;
}
const Atom* AtomContainer::getAtom(Position position) const
throw()
{
return ((AtomContainer *)this)->getAtom(position);
}
Atom* AtomContainer::getAtom(const String& name)
throw()
{
for (AtomIterator atom_it = beginAtom(); !atom_it.isEnd(); ++atom_it)
{
if ((*atom_it).getName() == name)
{
return &(*atom_it);
}
}
return 0;
}
const Atom* AtomContainer::getAtom(const String& name) const
throw()
{
return ((AtomContainer *)this)->getAtom(name);
}
Size AtomContainer::countAtomContainers() const
throw()
{
Size size = 0;
for (AtomContainerConstIterator atom_container_it = ++beginAtomContainer();
!atom_container_it.isEnd();++atom_container_it)
{
++size;
}
return size;
}
Size AtomContainer::countAtoms() const
throw()
{
Size size = 0;
for (AtomConstIterator atom_it = beginAtom(); !atom_it.isEnd(); ++atom_it)
{
++size;
}
return size;
}
Size AtomContainer::countBonds() const
throw()
{
Size size = 0;
AtomConstIterator atom_it;
Atom::BondConstIterator bond_it;
BALL_FOREACH_BOND(*this, atom_it, bond_it)
{
++size;
}
return size;
}
Size AtomContainer::countInterBonds() const
throw()
{
Size size = 0;
AtomConstIterator atom_it;
Atom::BondConstIterator bond_it;
BALL_FOREACH_INTERBOND(*this, atom_it, bond_it)
{
++size;
}
return size;
}
Size AtomContainer::countIntraBonds() const
throw()
{
Size size = 0;
AtomConstIterator atom_it;
Atom::BondConstIterator bond_it;
BALL_FOREACH_INTRABOND(*this, atom_it, bond_it)
{
++size;
}
return size;
}
void AtomContainer::prepend(Atom& atom)
throw()
{
Composite::prependChild(atom);
}
void AtomContainer::append(Atom &atom)
throw()
{
Composite::appendChild(atom);
}
void AtomContainer::insert(Atom &atom)
throw()
{
append(atom);
}
void AtomContainer::insertBefore(Atom &atom, Composite& before)
throw()
{
before.Composite::insertBefore(atom);
}
void AtomContainer::insertAfter(Atom& atom, Composite &after)
throw()
{
after.Composite::insertAfter(atom);
}
bool AtomContainer::remove(Atom& atom)
throw()
{
return Composite::removeChild(atom);
}
void AtomContainer::prepend(AtomContainer& atom_container)
throw()
{
Composite::prependChild(atom_container);
}
void AtomContainer::append(AtomContainer& atom_container)
throw()
{
Composite::appendChild(atom_container);
}
void AtomContainer::insert(AtomContainer& atom_container)
throw()
{
append(atom_container);
}
void AtomContainer::insertBefore(AtomContainer& atom_container, Composite& before)
throw()
{
before.Composite::insertBefore(atom_container);
}
void AtomContainer::insertAfter(AtomContainer& atom_container, Composite& after)
throw()
{
after.Composite::insertAfter(atom_container);
}
void AtomContainer::spliceBefore(AtomContainer& atom_container)
throw()
{
Composite::spliceBefore(atom_container);
}
void AtomContainer::spliceAfter(AtomContainer& atom_container)
throw()
{
Composite::spliceAfter(atom_container);
}
void AtomContainer::splice(AtomContainer& atom_container)
throw()
{
Composite::splice(atom_container);
}
bool AtomContainer::remove(AtomContainer& atom_container)
throw()
{
return Composite::removeChild(atom_container);
}
void AtomContainer::destroyBonds()
throw()
{
for (AtomIterator atom_it = beginAtom(); !atom_it.isEnd(); ++atom_it)
{
(*atom_it).destroyBonds();
}
}
bool AtomContainer::isSubAtomContainerOf(const AtomContainer& atom_container) const
throw()
{
return atom_container.isAncestorOf(*this);
}
bool AtomContainer::isSuperAtomContainerOf(const AtomContainer& atom_container) const
throw()
{
return isAncestorOf(atom_container);
}
bool AtomContainer::isValid() const
throw()
{
return (Composite::isValid() && PropertyManager::isValid() && name_.isValid());
}
void AtomContainer::dump(ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
Composite::dump(s, depth);
BALL_DUMP_DEPTH(s, depth);
s << " name: " << name_ << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
bool AtomContainer::applyInterBond(UnaryProcessor<Bond>& processor)
throw()
{
if (processor.start() == false)
{
return false;
}
Processor::Result result;
AtomIterator atom_it;
Atom::BondIterator bond_it;
BALL_FOREACH_INTERBOND(*this, atom_it, bond_it)
{
result = processor(*bond_it);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK) ? true : false;
}
}
return processor.finish();
}
bool AtomContainer::applyIntraBond(UnaryProcessor<Bond> &processor)
throw()
{
if (processor.start() == false)
{
return false;
}
Processor::Result result;
AtomIterator atom_it;
Atom::BondIterator bond_it;
BALL_FOREACH_INTRABOND(*this, atom_it, bond_it)
{
result = processor(*bond_it);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK) ? true : false;
}
}
return processor.finish();
}
bool AtomContainer::operator == (const AtomContainer& atom_container) const
throw()
{
return(Object::operator == (atom_container));
}
bool AtomContainer::operator != (const AtomContainer& atom_container) const
throw()
{
return ! (*this == atom_container);
}
} // namespace BALL
<commit_msg>removed: obsolete code<commit_after>// $Id: atomContainer.C,v 1.11 2001/07/15 20:41:33 oliver Exp $
#include <BALL/KERNEL/atomContainer.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/global.h>
#include <BALL/KERNEL/molecule.h>
using namespace std;
namespace BALL
{
AtomContainer::AtomContainer()
throw()
: Composite(),
PropertyManager(),
name_(BALL_ATOMCONTAINER_DEFAULT_NAME)
{
}
AtomContainer::AtomContainer(const AtomContainer& atom_container, bool deep)
throw()
: Composite(),
PropertyManager(),
name_()
{
set(atom_container, deep);
}
AtomContainer::AtomContainer(const String& name)
throw()
: Composite(),
PropertyManager(),
name_(name)
{
}
AtomContainer::~AtomContainer()
throw()
{
destroy();
}
void AtomContainer::clear()
throw()
{
Composite::clear();
PropertyManager::clear();
name_ = BALL_ATOMCONTAINER_DEFAULT_NAME;
}
void AtomContainer::destroy()
throw()
{
Composite::destroy();
PropertyManager::destroy();
name_ = BALL_ATOMCONTAINER_DEFAULT_NAME;
}
void AtomContainer::persistentWrite(PersistenceManager& pm, const char* name) const
throw(Exception::GeneralException)
{
pm.writeObjectHeader(this, name);
Composite::persistentWrite(pm);
pm.writeStorableObject(*(PropertyManager*)this, "PropertyManager");
pm.writePrimitive(name_, "name_");
pm.writeObjectTrailer(name);
}
void AtomContainer::persistentRead(PersistenceManager& pm)
throw(Exception::GeneralException)
{
pm.checkObjectHeader(RTTI::getStreamName<Composite>());
Composite::persistentRead(pm);
pm.checkObjectTrailer(0);
pm.readStorableObject(*(PropertyManager*)this, "PropertyManager");
pm.readPrimitive(name_, "name_");
}
void AtomContainer::set(const AtomContainer& atom_container, bool deep)
throw()
{
bool clone_them = clone_bonds;
clone_bonds = false;
Composite::set(atom_container, deep);
PropertyManager::set(atom_container);
name_ = atom_container.name_;
// clone the bonds only of we are the outmost set method
// involved!
if (clone_them && deep)
{
BALL::cloneBonds(atom_container, *this);
}
clone_bonds = clone_them;
}
const AtomContainer& AtomContainer::operator = (const AtomContainer& atom_container)
throw()
{
set(atom_container);
return *this;
}
void AtomContainer::get(AtomContainer& atom_container, bool deep) const
throw()
{
atom_container.set(*this, deep);
}
void AtomContainer::swap(AtomContainer& atom_container)
throw()
{
Composite::swap(atom_container);
PropertyManager::swap(atom_container);
name_.swap(atom_container.name_);
}
void AtomContainer::setName(const String& name)
throw()
{
name_ = name;
}
const String& AtomContainer::getName() const
throw()
{
return name_;
}
AtomContainer* AtomContainer::getSuperAtomContainer()
throw()
{
for (Composite::AncestorIterator ancestor_it = beginAncestor();
!ancestor_it.isEnd(); ++ancestor_it)
{
if (RTTI::isKindOf<AtomContainer>(*ancestor_it) == true)
{
return (AtomContainer *)&*ancestor_it;
}
}
return 0;
}
const AtomContainer* AtomContainer::getSuperAtomContainer() const
throw()
{
return ((AtomContainer *)this)->getSuperAtomContainer();
}
AtomContainer* AtomContainer::getAtomContainer(Position position)
throw()
{
for (AtomContainerIterator atom_container_it = ++beginAtomContainer();
!atom_container_it.isEnd(); ++atom_container_it)
{
if (position-- == 0)
{
return &(*atom_container_it);
}
}
return 0;
}
const AtomContainer* AtomContainer::getAtomContainer(Position position) const
throw()
{
return ((AtomContainer *)this)->getAtomContainer(position);
}
Atom* AtomContainer::getAtom(Position position)
throw()
{
for (AtomIterator atom_it = beginAtom(); !atom_it.isEnd(); ++atom_it)
{
if (position-- == 0)
{
return &(*atom_it);
}
}
return 0;
}
const Atom* AtomContainer::getAtom(Position position) const
throw()
{
return ((AtomContainer *)this)->getAtom(position);
}
Atom* AtomContainer::getAtom(const String& name)
throw()
{
for (AtomIterator atom_it = beginAtom(); !atom_it.isEnd(); ++atom_it)
{
if ((*atom_it).getName() == name)
{
return &(*atom_it);
}
}
return 0;
}
const Atom* AtomContainer::getAtom(const String& name) const
throw()
{
return ((AtomContainer *)this)->getAtom(name);
}
Size AtomContainer::countAtomContainers() const
throw()
{
Size size = 0;
for (AtomContainerConstIterator atom_container_it = ++beginAtomContainer();
!atom_container_it.isEnd();++atom_container_it)
{
++size;
}
return size;
}
Size AtomContainer::countAtoms() const
throw()
{
Size size = 0;
for (AtomConstIterator atom_it = beginAtom(); !atom_it.isEnd(); ++atom_it)
{
++size;
}
return size;
}
Size AtomContainer::countBonds() const
throw()
{
Size size = 0;
AtomConstIterator atom_it;
Atom::BondConstIterator bond_it;
BALL_FOREACH_BOND(*this, atom_it, bond_it)
{
++size;
}
return size;
}
Size AtomContainer::countInterBonds() const
throw()
{
Size size = 0;
AtomConstIterator atom_it;
Atom::BondConstIterator bond_it;
BALL_FOREACH_INTERBOND(*this, atom_it, bond_it)
{
++size;
}
return size;
}
Size AtomContainer::countIntraBonds() const
throw()
{
Size size = 0;
AtomConstIterator atom_it;
Atom::BondConstIterator bond_it;
BALL_FOREACH_INTRABOND(*this, atom_it, bond_it)
{
++size;
}
return size;
}
void AtomContainer::prepend(Atom& atom)
throw()
{
Composite::prependChild(atom);
}
void AtomContainer::append(Atom &atom)
throw()
{
Composite::appendChild(atom);
}
void AtomContainer::insert(Atom &atom)
throw()
{
append(atom);
}
void AtomContainer::insertBefore(Atom &atom, Composite& before)
throw()
{
before.Composite::insertBefore(atom);
}
void AtomContainer::insertAfter(Atom& atom, Composite &after)
throw()
{
after.Composite::insertAfter(atom);
}
bool AtomContainer::remove(Atom& atom)
throw()
{
return Composite::removeChild(atom);
}
void AtomContainer::prepend(AtomContainer& atom_container)
throw()
{
Composite::prependChild(atom_container);
}
void AtomContainer::append(AtomContainer& atom_container)
throw()
{
Composite::appendChild(atom_container);
}
void AtomContainer::insert(AtomContainer& atom_container)
throw()
{
append(atom_container);
}
void AtomContainer::insertBefore(AtomContainer& atom_container, Composite& before)
throw()
{
before.Composite::insertBefore(atom_container);
}
void AtomContainer::insertAfter(AtomContainer& atom_container, Composite& after)
throw()
{
after.Composite::insertAfter(atom_container);
}
void AtomContainer::spliceBefore(AtomContainer& atom_container)
throw()
{
Composite::spliceBefore(atom_container);
}
void AtomContainer::spliceAfter(AtomContainer& atom_container)
throw()
{
Composite::spliceAfter(atom_container);
}
void AtomContainer::splice(AtomContainer& atom_container)
throw()
{
Composite::splice(atom_container);
}
bool AtomContainer::remove(AtomContainer& atom_container)
throw()
{
return Composite::removeChild(atom_container);
}
void AtomContainer::destroyBonds()
throw()
{
for (AtomIterator atom_it = beginAtom(); !atom_it.isEnd(); ++atom_it)
{
(*atom_it).destroyBonds();
}
}
bool AtomContainer::isSubAtomContainerOf(const AtomContainer& atom_container) const
throw()
{
return atom_container.isAncestorOf(*this);
}
bool AtomContainer::isSuperAtomContainerOf(const AtomContainer& atom_container) const
throw()
{
return isAncestorOf(atom_container);
}
bool AtomContainer::isValid() const
throw()
{
return (Composite::isValid() && PropertyManager::isValid() && name_.isValid());
}
void AtomContainer::dump(ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
Composite::dump(s, depth);
BALL_DUMP_DEPTH(s, depth);
s << " name: " << name_ << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
bool AtomContainer::applyInterBond(UnaryProcessor<Bond>& processor)
throw()
{
if (processor.start() == false)
{
return false;
}
Processor::Result result;
AtomIterator atom_it;
Atom::BondIterator bond_it;
BALL_FOREACH_INTERBOND(*this, atom_it, bond_it)
{
result = processor(*bond_it);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK) ? true : false;
}
}
return processor.finish();
}
bool AtomContainer::applyIntraBond(UnaryProcessor<Bond> &processor)
throw()
{
if (processor.start() == false)
{
return false;
}
Processor::Result result;
AtomIterator atom_it;
Atom::BondIterator bond_it;
BALL_FOREACH_INTRABOND(*this, atom_it, bond_it)
{
result = processor(*bond_it);
if (result <= Processor::BREAK)
{
return (result == Processor::BREAK) ? true : false;
}
}
return processor.finish();
}
bool AtomContainer::operator == (const AtomContainer& atom_container) const
throw()
{
return(Object::operator == (atom_container));
}
bool AtomContainer::operator != (const AtomContainer& atom_container) const
throw()
{
return ! (*this == atom_container);
}
} // namespace BALL
<|endoftext|>
|
<commit_before>/*
* Copyright © 2015 Christian Persch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* SECTION: vte-regex
* @short_description: Regex for matching and searching. Uses PCRE2 internally.
*
* Since: 0.44
*/
#include "config.h"
#include "vtemacros.h"
#include "vteenums.h"
#include "vteregex.h"
#ifdef WITH_PCRE2
#include "vtepcre2.h"
#endif /* WITH_PCRE2 */
#include "vteregexinternal.hh"
struct _VteRegex {
volatile int ref_count;
#ifdef WITH_PCRE2
pcre2_code_8 *code;
#endif /* WITH_PCRE2 */
};
#ifdef WITH_PCRE2
#define DEFAULT_COMPILE_OPTIONS (PCRE2_UTF)
#define JIT_OPTIONS (PCRE2_JIT_COMPLETE)
#define DEFAULT_MATCH_OPTIONS (0)
#else
#define DEFAULT_COMPILE_OPTIONS (0
#define JIT_OPTIONS (0)
#define DEFAULT_MATCH_OPTIONS (0)
#endif /* WITH_PCRE2 */
#ifdef WITH_PCRE2
static VteRegex *
regex_new(pcre2_code_8 *code)
{
VteRegex *regex;
regex = g_slice_new(VteRegex);
regex->ref_count = 1;
regex->code = code;
return regex;
}
static void
regex_free(VteRegex *regex)
{
pcre2_code_free_8(regex->code);
g_slice_free(VteRegex, regex);
}
static gboolean
set_gerror_from_pcre_error(int errcode,
GError **error)
{
PCRE2_UCHAR8 buf[128];
int n;
n = pcre2_get_error_message_8(errcode, buf, sizeof (buf));
g_assert(n >= 0);
g_set_error_literal(error, VTE_REGEX_ERROR, errcode, (const char*)buf);
return FALSE;
}
#else
static gboolean
set_unsupported_error(GError **error)
{
g_set_error_literal(error, VTE_REGEX_ERROR, VTE_REGEX_ERROR_NOT_SUPPORTED,
"PCRE2 not supported");
return FALSE;
}
#endif /* WITH_PCRE2 */
G_DEFINE_BOXED_TYPE(VteRegex, vte_regex,
vte_regex_ref, (GBoxedFreeFunc)vte_regex_unref)
G_DEFINE_QUARK(vte-regex-error, vte_regex_error)
/**
* vte_regex_ref:
* @regex: (transfer none): a #VteRegex
*
* Increases the reference count of @regex by one.
*
* Returns: @regex
*/
VteRegex *
vte_regex_ref(VteRegex *regex)
{
g_return_val_if_fail (regex, NULL);
#ifdef WITH_PCRE2
g_atomic_int_inc (®ex->ref_count);
#endif
return regex;
}
/**
* vte_regex_ref:
* @regex: (transfer full): a #VteRegex
*
* Decreases the reference count of @regex by one, and frees @regex
* if the refcount reaches zero.
*
* Returns: %NULL
*/
VteRegex *
vte_regex_unref(VteRegex *regex)
{
g_return_val_if_fail (regex, NULL);
#ifdef WITH_PCRE2
if (g_atomic_int_dec_and_test (®ex->ref_count))
regex_free (regex);
#endif
return NULL;
}
/**
* vte_regex_new:
* @pattern: a regex pattern string
* @pattern_length: the length of @pattern in bytes, or -1 if the
* string is NUL-terminated and the length is unknown
* @flags: PCRE2 compile flags
* @error: (allow-none): return location for a #GError, or %NULL
*
* Compiles @pattern into a regex. See man:pcre2pattern(3) for information
* about the supported regex language.
*
* The regex will be compiled using %PCRE2_UTF and possibly other flags, in
* addition to the flags supplied in @flags.
*
* Returns: (transfer full): a newly created #VteRegex, or %NULL with @error filled in
*/
VteRegex *
vte_regex_new(const char *pattern,
gssize pattern_length,
guint32 flags,
GError **error)
{
#ifdef WITH_PCRE2
pcre2_code_8 *code;
int r, errcode;
guint32 v;
PCRE2_SIZE erroffset;
g_return_val_if_fail(pattern != NULL, NULL);
g_return_val_if_fail(pattern_length >= -1, NULL);
g_return_val_if_fail(error == NULL || *error == NULL, NULL);
/* Check library compatibility */
r = pcre2_config_8(PCRE2_CONFIG_UNICODE, &v);
if (r != 0 || v != 1) {
g_set_error(error, VTE_REGEX_ERROR, VTE_REGEX_ERROR_INCOMPATIBLE,
"PCRE2 library was built without unicode support");
return NULL;
}
code = pcre2_compile_8((PCRE2_SPTR8)pattern,
pattern_length >= 0 ? pattern_length : PCRE2_ZERO_TERMINATED,
(uint32_t)flags |
PCRE2_UTF |
(flags & PCRE2_UTF ? PCRE2_NO_UTF_CHECK : 0) |
PCRE2_NEVER_BACKSLASH_C,
&errcode, &erroffset,
NULL);
if (code == 0) {
set_gerror_from_pcre_error(errcode, error);
g_prefix_error(error, "Failed to compile pattern to regex at %" G_GSIZE_FORMAT ":",
erroffset);
return NULL;
}
return regex_new(code);
#else
set_unsupported_error(error);
return NULL;
#endif /* WITH_PCRE2 */
}
#if 0
/*
* vte_regex_new_pcre:
* @code: a #pcre2_code_8
*
* Creates a new #VteRegex for @code. @code must have been compiled with
* %PCRE2_UTF and %PCRE2_NEVER_BACKSLASH_C.
*
* Returns: (transfer full): a newly created #VteRegex, or %NULL if VTE
* was not compiled with PCRE2 support.
*/
VteRegex *
vte_regex_new_pcre(pcre2_code_8 *code,
GError **error)
{
#ifdef WITH_PCRE2
guint32 flags;
g_return_val_if_fail(code != NULL, NULL);
g_return_val_if_fail(error == NULL || *error == NULL, NULL);
pcre2_pattern_info_8(code, PCRE2_INFO_ALLOPTIONS, &flags);
g_return_val_if_fail(flags & PCRE2_UTF, NULL);
g_return_val_if_fail(flags & PCRE2_NEVER_BACKSLASH_C, NULL);
return regex_new(code);
#else
set_unsupported_error(error);
return NULL;
#endif
}
#endif
#ifdef WITH_PCRE2
/*
* _vte_regex_get_pcre:
* @regex: a #VteRegex
*
*
* Returns: the #pcre2_code_8 from @regex
*/
const pcre2_code_8 *
_vte_regex_get_pcre(VteRegex *regex)
{
#ifdef WITH_PCRE2
g_return_val_if_fail(regex != NULL, NULL);
return regex->code;
#else
return NULL;
#endif
}
#endif
/**
* vte_regex_jit:
* @regex: a #VteRegex
*
* If the platform supports JITing, JIT compiles @regex.
*
* Returns: %TRUE if JITing succeeded, or %FALSE with @error filled in
*/
gboolean
vte_regex_jit(VteRegex *regex,
guint flags,
GError **error)
{
#ifdef WITH_PCRE2
int r;
g_return_val_if_fail(regex != NULL, FALSE);
r = pcre2_jit_compile_8(regex->code, flags);
return set_gerror_from_pcre_error(r, error);
#else
return set_unsupported_error(error);
#endif /* WITH_PCRE2 */
}
/*
* _vte_regex_get_jited:
*
* Note: We can't tell if the regex has been JITed for a particular mode,
* just if it has been JITed at all.
*
* Returns: %TRUE iff the regex has been JITed
*/
gboolean
_vte_regex_get_jited(VteRegex *regex)
{
#ifdef WITH_PCRE2
PCRE2_SIZE s;
int r;
g_return_val_if_fail(regex != NULL, FALSE);
r = pcre2_pattern_info_8(regex->code, PCRE2_INFO_JITSIZE, &s);
return r == 0 && s != 0;
#else
return FALSE;
#endif
}
<commit_msg>regex: Fix pcre2_jit_compile return value check<commit_after>/*
* Copyright © 2015 Christian Persch
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* SECTION: vte-regex
* @short_description: Regex for matching and searching. Uses PCRE2 internally.
*
* Since: 0.44
*/
#include "config.h"
#include "vtemacros.h"
#include "vteenums.h"
#include "vteregex.h"
#ifdef WITH_PCRE2
#include "vtepcre2.h"
#endif /* WITH_PCRE2 */
#include "vteregexinternal.hh"
struct _VteRegex {
volatile int ref_count;
#ifdef WITH_PCRE2
pcre2_code_8 *code;
#endif /* WITH_PCRE2 */
};
#ifdef WITH_PCRE2
#define DEFAULT_COMPILE_OPTIONS (PCRE2_UTF)
#define JIT_OPTIONS (PCRE2_JIT_COMPLETE)
#define DEFAULT_MATCH_OPTIONS (0)
#else
#define DEFAULT_COMPILE_OPTIONS (0
#define JIT_OPTIONS (0)
#define DEFAULT_MATCH_OPTIONS (0)
#endif /* WITH_PCRE2 */
#ifdef WITH_PCRE2
static VteRegex *
regex_new(pcre2_code_8 *code)
{
VteRegex *regex;
regex = g_slice_new(VteRegex);
regex->ref_count = 1;
regex->code = code;
return regex;
}
static void
regex_free(VteRegex *regex)
{
pcre2_code_free_8(regex->code);
g_slice_free(VteRegex, regex);
}
static gboolean
set_gerror_from_pcre_error(int errcode,
GError **error)
{
PCRE2_UCHAR8 buf[128];
int n;
n = pcre2_get_error_message_8(errcode, buf, sizeof (buf));
g_assert(n >= 0);
g_set_error_literal(error, VTE_REGEX_ERROR, errcode, (const char*)buf);
return FALSE;
}
#else
static gboolean
set_unsupported_error(GError **error)
{
g_set_error_literal(error, VTE_REGEX_ERROR, VTE_REGEX_ERROR_NOT_SUPPORTED,
"PCRE2 not supported");
return FALSE;
}
#endif /* WITH_PCRE2 */
G_DEFINE_BOXED_TYPE(VteRegex, vte_regex,
vte_regex_ref, (GBoxedFreeFunc)vte_regex_unref)
G_DEFINE_QUARK(vte-regex-error, vte_regex_error)
/**
* vte_regex_ref:
* @regex: (transfer none): a #VteRegex
*
* Increases the reference count of @regex by one.
*
* Returns: @regex
*/
VteRegex *
vte_regex_ref(VteRegex *regex)
{
g_return_val_if_fail (regex, NULL);
#ifdef WITH_PCRE2
g_atomic_int_inc (®ex->ref_count);
#endif
return regex;
}
/**
* vte_regex_ref:
* @regex: (transfer full): a #VteRegex
*
* Decreases the reference count of @regex by one, and frees @regex
* if the refcount reaches zero.
*
* Returns: %NULL
*/
VteRegex *
vte_regex_unref(VteRegex *regex)
{
g_return_val_if_fail (regex, NULL);
#ifdef WITH_PCRE2
if (g_atomic_int_dec_and_test (®ex->ref_count))
regex_free (regex);
#endif
return NULL;
}
/**
* vte_regex_new:
* @pattern: a regex pattern string
* @pattern_length: the length of @pattern in bytes, or -1 if the
* string is NUL-terminated and the length is unknown
* @flags: PCRE2 compile flags
* @error: (allow-none): return location for a #GError, or %NULL
*
* Compiles @pattern into a regex. See man:pcre2pattern(3) for information
* about the supported regex language.
*
* The regex will be compiled using %PCRE2_UTF and possibly other flags, in
* addition to the flags supplied in @flags.
*
* Returns: (transfer full): a newly created #VteRegex, or %NULL with @error filled in
*/
VteRegex *
vte_regex_new(const char *pattern,
gssize pattern_length,
guint32 flags,
GError **error)
{
#ifdef WITH_PCRE2
pcre2_code_8 *code;
int r, errcode;
guint32 v;
PCRE2_SIZE erroffset;
g_return_val_if_fail(pattern != NULL, NULL);
g_return_val_if_fail(pattern_length >= -1, NULL);
g_return_val_if_fail(error == NULL || *error == NULL, NULL);
/* Check library compatibility */
r = pcre2_config_8(PCRE2_CONFIG_UNICODE, &v);
if (r != 0 || v != 1) {
g_set_error(error, VTE_REGEX_ERROR, VTE_REGEX_ERROR_INCOMPATIBLE,
"PCRE2 library was built without unicode support");
return NULL;
}
code = pcre2_compile_8((PCRE2_SPTR8)pattern,
pattern_length >= 0 ? pattern_length : PCRE2_ZERO_TERMINATED,
(uint32_t)flags |
PCRE2_UTF |
(flags & PCRE2_UTF ? PCRE2_NO_UTF_CHECK : 0) |
PCRE2_NEVER_BACKSLASH_C,
&errcode, &erroffset,
NULL);
if (code == 0) {
set_gerror_from_pcre_error(errcode, error);
g_prefix_error(error, "Failed to compile pattern to regex at %" G_GSIZE_FORMAT ":",
erroffset);
return NULL;
}
return regex_new(code);
#else
set_unsupported_error(error);
return NULL;
#endif /* WITH_PCRE2 */
}
#if 0
/*
* vte_regex_new_pcre:
* @code: a #pcre2_code_8
*
* Creates a new #VteRegex for @code. @code must have been compiled with
* %PCRE2_UTF and %PCRE2_NEVER_BACKSLASH_C.
*
* Returns: (transfer full): a newly created #VteRegex, or %NULL if VTE
* was not compiled with PCRE2 support.
*/
VteRegex *
vte_regex_new_pcre(pcre2_code_8 *code,
GError **error)
{
#ifdef WITH_PCRE2
guint32 flags;
g_return_val_if_fail(code != NULL, NULL);
g_return_val_if_fail(error == NULL || *error == NULL, NULL);
pcre2_pattern_info_8(code, PCRE2_INFO_ALLOPTIONS, &flags);
g_return_val_if_fail(flags & PCRE2_UTF, NULL);
g_return_val_if_fail(flags & PCRE2_NEVER_BACKSLASH_C, NULL);
return regex_new(code);
#else
set_unsupported_error(error);
return NULL;
#endif
}
#endif
#ifdef WITH_PCRE2
/*
* _vte_regex_get_pcre:
* @regex: a #VteRegex
*
*
* Returns: the #pcre2_code_8 from @regex
*/
const pcre2_code_8 *
_vte_regex_get_pcre(VteRegex *regex)
{
#ifdef WITH_PCRE2
g_return_val_if_fail(regex != NULL, NULL);
return regex->code;
#else
return NULL;
#endif
}
#endif
/**
* vte_regex_jit:
* @regex: a #VteRegex
*
* If the platform supports JITing, JIT compiles @regex.
*
* Returns: %TRUE if JITing succeeded, or %FALSE with @error filled in
*/
gboolean
vte_regex_jit(VteRegex *regex,
guint flags,
GError **error)
{
#ifdef WITH_PCRE2
int r;
g_return_val_if_fail(regex != NULL, FALSE);
r = pcre2_jit_compile_8(regex->code, flags);
if (r < 0)
return set_gerror_from_pcre_error(r, error);
return TRUE;
#else
return set_unsupported_error(error);
#endif /* WITH_PCRE2 */
}
/*
* _vte_regex_get_jited:
*
* Note: We can't tell if the regex has been JITed for a particular mode,
* just if it has been JITed at all.
*
* Returns: %TRUE iff the regex has been JITed
*/
gboolean
_vte_regex_get_jited(VteRegex *regex)
{
#ifdef WITH_PCRE2
PCRE2_SIZE s;
int r;
g_return_val_if_fail(regex != NULL, FALSE);
r = pcre2_pattern_info_8(regex->code, PCRE2_INFO_JITSIZE, &s);
return r == 0 && s != 0;
#else
return FALSE;
#endif
}
<|endoftext|>
|
<commit_before>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "base/sys_info.h"
#include "base/logging.h"
namespace base {
//static
std::string SysInfo::operatingSystemName()
{
NOTIMPLEMENTED();
return std::string();
}
// static
std::string SysInfo::operatingSystemVersion()
{
NOTIMPLEMENTED();
return std::string();
}
// static
std::string SysInfo::operatingSystemArchitecture()
{
NOTIMPLEMENTED();
return std::string();
}
// static
std::string SysInfo::operatingSystemDir()
{
NOTIMPLEMENTED();
return std::string();
}
// static
uint64_t SysInfo::uptime()
{
NOTIMPLEMENTED();
return 0;
}
// static
std::string SysInfo::computerName()
{
NOTIMPLEMENTED();
return std::string();
}
// static
std::string SysInfo::computerDomain()
{
NOTIMPLEMENTED();
return std::string();
}
// static
std::string SysInfo::computerWorkgroup()
{
NOTIMPLEMENTED();
return std::string();
}
// static
int SysInfo::processorPackages()
{
NOTIMPLEMENTED();
return 0;
}
// static
int SysInfo::processorCores()
{
NOTIMPLEMENTED();
return 0;
}
// static
int SysInfo::processorThreads()
{
NOTIMPLEMENTED();
return 0;
}
} // namespace base
<commit_msg>Implement operatingSystemName/operatingSystemVersion/uptime/computerName methods for Linux.<commit_after>//
// Aspia Project
// Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru>
//
// 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 <https://www.gnu.org/licenses/>.
//
#include "base/sys_info.h"
#include "base/logging.h"
#include <sys/param.h>
#include <sys/sysinfo.h>
#include <sys/utsname.h>
#include <unistd.h>
namespace base {
//static
std::string SysInfo::operatingSystemName()
{
struct utsname info;
if (uname(&info) < 0)
return std::string();
return std::string(info.sysname);
}
// static
std::string SysInfo::operatingSystemVersion()
{
struct utsname info;
if (uname(&info) < 0)
return std::string();
return std::string(info.release);
}
// static
std::string SysInfo::operatingSystemArchitecture()
{
NOTIMPLEMENTED();
return std::string();
}
// static
std::string SysInfo::operatingSystemDir()
{
NOTIMPLEMENTED();
return std::string();
}
// static
uint64_t SysInfo::uptime()
{
struct sysinfo info;
if (sysinfo(&info) < 0)
return 0;
return info.uptime;
}
// static
std::string SysInfo::computerName()
{
char buffer[256];
if (gethostname(buffer, std::size(buffer)) < 0)
return std::string();
return std::string(buffer);
}
// static
std::string SysInfo::computerDomain()
{
NOTIMPLEMENTED();
return std::string();
}
// static
std::string SysInfo::computerWorkgroup()
{
NOTIMPLEMENTED();
return std::string();
}
// static
int SysInfo::processorPackages()
{
NOTIMPLEMENTED();
return 0;
}
// static
int SysInfo::processorCores()
{
NOTIMPLEMENTED();
return 0;
}
// static
int SysInfo::processorThreads()
{
NOTIMPLEMENTED();
return 0;
}
} // namespace base
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/ivf_video_source.h"
#include "test/util.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vpx_mem/vpx_mem.h"
namespace {
struct DecodeParam {
int threads;
const char *filename;
};
std::ostream &operator<<(std::ostream &os, const DecodeParam &dp) {
return os << "threads: " << dp.threads << " file: " << dp.filename;
}
class InvalidFileTest
: public ::libvpx_test::DecoderTest,
public ::libvpx_test::CodecTestWithParam<DecodeParam> {
protected:
InvalidFileTest() : DecoderTest(GET_PARAM(0)), res_file_(NULL) {}
virtual ~InvalidFileTest() {
if (res_file_ != NULL)
fclose(res_file_);
}
void OpenResFile(const std::string &res_file_name_) {
res_file_ = libvpx_test::OpenTestDataFile(res_file_name_);
ASSERT_TRUE(res_file_ != NULL) << "Result file open failed. Filename: "
<< res_file_name_;
}
virtual bool HandleDecodeResult(
const vpx_codec_err_t res_dec,
const libvpx_test::CompressedVideoSource &video,
libvpx_test::Decoder *decoder) {
EXPECT_TRUE(res_file_ != NULL);
int expected_res_dec;
// Read integer result.
const int res = fscanf(res_file_, "%d", &expected_res_dec);
EXPECT_NE(res, EOF) << "Read result data failed";
// Check results match.
EXPECT_EQ(expected_res_dec, res_dec)
<< "Results don't match: frame number = " << video.frame_number()
<< ". (" << decoder->DecodeError() << ")";
return !HasFailure();
}
void RunTest() {
const DecodeParam input = GET_PARAM(1);
libvpx_test::CompressedVideoSource *video = NULL;
vpx_codec_dec_cfg_t cfg = {0};
cfg.threads = input.threads;
const std::string filename = input.filename;
// Open compressed video file.
if (filename.substr(filename.length() - 3, 3) == "ivf") {
video = new libvpx_test::IVFVideoSource(filename);
} else if (filename.substr(filename.length() - 4, 4) == "webm") {
#if CONFIG_WEBM_IO
video = new libvpx_test::WebMVideoSource(filename);
#else
fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n",
filename.c_str());
return;
#endif
}
video->Init();
// Construct result file name. The file holds a list of expected integer
// results, one for each decoded frame. Any result that doesn't match
// the files list will cause a test failure.
const std::string res_filename = filename + ".res";
OpenResFile(res_filename);
// Decode frame, and check the md5 matching.
ASSERT_NO_FATAL_FAILURE(RunLoop(video, cfg));
delete video;
}
private:
FILE *res_file_;
};
TEST_P(InvalidFileTest, ReturnCode) {
RunTest();
}
const DecodeParam kVP9InvalidFileTests[] = {
{1, "invalid-vp90-02-v2.webm"},
{1, "invalid-vp90-2-00-quantizer-00.webm.ivf.s5861_r01-05_b6-.v2.ivf"},
{1, "invalid-vp90-03-v2.webm"},
{1, "invalid-vp90-2-00-quantizer-11.webm.ivf.s52984_r01-05_b6-.ivf"},
{1, "invalid-vp90-2-00-quantizer-11.webm.ivf.s52984_r01-05_b6-z.ivf"},
};
VP9_INSTANTIATE_TEST_CASE(InvalidFileTest,
::testing::ValuesIn(kVP9InvalidFileTests));
// This class will include test vectors that are expected to fail
// peek. However they are still expected to have no fatal failures.
class InvalidFileInvalidPeekTest : public InvalidFileTest {
protected:
InvalidFileInvalidPeekTest() : InvalidFileTest() {}
virtual void HandlePeekResult(libvpx_test::Decoder *const decoder,
libvpx_test::CompressedVideoSource *video,
const vpx_codec_err_t res_peek) {}
};
TEST_P(InvalidFileInvalidPeekTest, ReturnCode) {
RunTest();
}
const DecodeParam kVP9InvalidFileInvalidPeekTests[] = {
{1, "invalid-vp90-01-v2.webm"},
};
VP9_INSTANTIATE_TEST_CASE(InvalidFileInvalidPeekTest,
::testing::ValuesIn(kVP9InvalidFileInvalidPeekTests));
const DecodeParam kMultiThreadedVP9InvalidFileTests[] = {
{4, "invalid-vp90-2-08-tile_1x4_frame_parallel_all_key.webm"},
};
INSTANTIATE_TEST_CASE_P(
VP9MultiThreaded, InvalidFileTest,
::testing::Combine(
::testing::Values(
static_cast<const libvpx_test::CodecFactory*>(&libvpx_test::kVP9)),
::testing::ValuesIn(kMultiThreadedVP9InvalidFileTests)));
} // namespace
<commit_msg>invalid_file_test.cc: remove unused param warnings<commit_after>/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/ivf_video_source.h"
#include "test/util.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vpx_mem/vpx_mem.h"
namespace {
struct DecodeParam {
int threads;
const char *filename;
};
std::ostream &operator<<(std::ostream &os, const DecodeParam &dp) {
return os << "threads: " << dp.threads << " file: " << dp.filename;
}
class InvalidFileTest
: public ::libvpx_test::DecoderTest,
public ::libvpx_test::CodecTestWithParam<DecodeParam> {
protected:
InvalidFileTest() : DecoderTest(GET_PARAM(0)), res_file_(NULL) {}
virtual ~InvalidFileTest() {
if (res_file_ != NULL)
fclose(res_file_);
}
void OpenResFile(const std::string &res_file_name_) {
res_file_ = libvpx_test::OpenTestDataFile(res_file_name_);
ASSERT_TRUE(res_file_ != NULL) << "Result file open failed. Filename: "
<< res_file_name_;
}
virtual bool HandleDecodeResult(
const vpx_codec_err_t res_dec,
const libvpx_test::CompressedVideoSource &video,
libvpx_test::Decoder *decoder) {
EXPECT_TRUE(res_file_ != NULL);
int expected_res_dec;
// Read integer result.
const int res = fscanf(res_file_, "%d", &expected_res_dec);
EXPECT_NE(res, EOF) << "Read result data failed";
// Check results match.
EXPECT_EQ(expected_res_dec, res_dec)
<< "Results don't match: frame number = " << video.frame_number()
<< ". (" << decoder->DecodeError() << ")";
return !HasFailure();
}
void RunTest() {
const DecodeParam input = GET_PARAM(1);
libvpx_test::CompressedVideoSource *video = NULL;
vpx_codec_dec_cfg_t cfg = {0};
cfg.threads = input.threads;
const std::string filename = input.filename;
// Open compressed video file.
if (filename.substr(filename.length() - 3, 3) == "ivf") {
video = new libvpx_test::IVFVideoSource(filename);
} else if (filename.substr(filename.length() - 4, 4) == "webm") {
#if CONFIG_WEBM_IO
video = new libvpx_test::WebMVideoSource(filename);
#else
fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n",
filename.c_str());
return;
#endif
}
video->Init();
// Construct result file name. The file holds a list of expected integer
// results, one for each decoded frame. Any result that doesn't match
// the files list will cause a test failure.
const std::string res_filename = filename + ".res";
OpenResFile(res_filename);
// Decode frame, and check the md5 matching.
ASSERT_NO_FATAL_FAILURE(RunLoop(video, cfg));
delete video;
}
private:
FILE *res_file_;
};
TEST_P(InvalidFileTest, ReturnCode) {
RunTest();
}
const DecodeParam kVP9InvalidFileTests[] = {
{1, "invalid-vp90-02-v2.webm"},
{1, "invalid-vp90-2-00-quantizer-00.webm.ivf.s5861_r01-05_b6-.v2.ivf"},
{1, "invalid-vp90-03-v2.webm"},
{1, "invalid-vp90-2-00-quantizer-11.webm.ivf.s52984_r01-05_b6-.ivf"},
{1, "invalid-vp90-2-00-quantizer-11.webm.ivf.s52984_r01-05_b6-z.ivf"},
};
VP9_INSTANTIATE_TEST_CASE(InvalidFileTest,
::testing::ValuesIn(kVP9InvalidFileTests));
// This class will include test vectors that are expected to fail
// peek. However they are still expected to have no fatal failures.
class InvalidFileInvalidPeekTest : public InvalidFileTest {
protected:
InvalidFileInvalidPeekTest() : InvalidFileTest() {}
virtual void HandlePeekResult(libvpx_test::Decoder* /*decoder*/,
libvpx_test::CompressedVideoSource* /*video*/,
const vpx_codec_err_t /*res_peek*/) {}
};
TEST_P(InvalidFileInvalidPeekTest, ReturnCode) {
RunTest();
}
const DecodeParam kVP9InvalidFileInvalidPeekTests[] = {
{1, "invalid-vp90-01-v2.webm"},
};
VP9_INSTANTIATE_TEST_CASE(InvalidFileInvalidPeekTest,
::testing::ValuesIn(kVP9InvalidFileInvalidPeekTests));
const DecodeParam kMultiThreadedVP9InvalidFileTests[] = {
{4, "invalid-vp90-2-08-tile_1x4_frame_parallel_all_key.webm"},
};
INSTANTIATE_TEST_CASE_P(
VP9MultiThreaded, InvalidFileTest,
::testing::Combine(
::testing::Values(
static_cast<const libvpx_test::CodecFactory*>(&libvpx_test::kVP9)),
::testing::ValuesIn(kMultiThreadedVP9InvalidFileTests)));
} // namespace
<|endoftext|>
|
<commit_before>/*
* IceWM
*
* Copyright (C) 1997-2001 Marko Macek
*/
#include "config.h"
#include "wmbutton.h"
#include "wmframe.h"
#include "wmtitle.h"
#include "yxapp.h"
#include "yicon.h"
#include "yprefs.h"
#include "prefs.h"
#include "wpixmaps.h"
static YColor *titleButtonBg = 0;
static YColor *titleButtonFg = 0;
//!!! get rid of this
extern YColor *activeTitleBarBg;
extern YColor *inactiveTitleBarBg;
YFrameButton::YFrameButton(YWindow *parent,
bool right,
YFrameWindow *frame,
YAction action,
YAction action2):
YButton(desktop, actionNull),
fFrame(frame),
fRight(right),
fAction(action),
fAction2(action2)
{
reparent(parent, 0, 0);
if (titleButtonBg == 0)
titleButtonBg = new YColor(clrNormalTitleButton);
if (titleButtonFg == 0)
titleButtonFg = new YColor(clrNormalTitleButtonText);
if (fAction == actionNull)
setPopup(frame->windowMenu());
if (right)
setWinGravity(NorthEastGravity);
setSize(0,0);
}
YFrameButton::~YFrameButton() {
}
void YFrameButton::handleButton(const XButtonEvent &button) {
if (button.type == ButtonPress &&
(buttonRaiseMask & (1 << (button.button - 1))))
{
if (!(button.state & ControlMask) && raiseOnClickButton) {
getFrame()->activate();
if (raiseOnClickButton && fAction != actionDepth)
getFrame()->wmRaise();
}
}
YButton::handleButton(button);
}
void YFrameButton::handleClick(const XButtonEvent &up, int count) {
if (fAction == actionNull && up.button == 1) {
if ((count % 2) == 0) {
setArmed(false, false);
getFrame()->wmClose();
}
} else if (up.button == 3 && (KEY_MODMASK(up.state) & (xapp->AltMask)) == 0) {
if (!isPopupActive())
getFrame()->popupSystemMenu(this, up.x_root, up.y_root,
YPopupWindow::pfCanFlipVertical |
YPopupWindow::pfCanFlipHorizontal);
}
}
void YFrameButton::handleBeginDrag(const XButtonEvent &down, const XMotionEvent &/*motion*/) {
if (down.button == 3 && getFrame()->canMove()) {
if (!isPopupActive()) {
YFrameTitleBar* tbar = getFrame()->titlebar();
getFrame()->startMoveSize(true, true,
0, 0,
down.x + x() + (tbar ? tbar->x() : 0),
down.y + y() + (tbar ? tbar->y() : 0));
}
}
}
void YFrameButton::setActions(YAction action, YAction action2) {
fAction2 = action2;
if (action != fAction) {
fAction = action;
repaint();
}
}
void YFrameButton::updatePopup() {
getFrame()->updateMenu();
}
void YFrameButton::actionPerformed(YAction /*action*/, unsigned int modifiers) {
if ((modifiers & ShiftMask) && fAction2 != actionNull)
getFrame()->actionPerformed(fAction2, modifiers);
else
getFrame()->actionPerformed(fAction, modifiers);
}
ref<YPixmap> YFrameButton::getPixmap(int pn) const {
if (fAction == actionMaximize)
return maximizePixmap[pn];
else if (fAction == actionMinimize)
return minimizePixmap[pn];
else if (fAction == actionRestore)
return restorePixmap[pn];
else if (fAction == actionClose)
return closePixmap[pn];
else if (fAction == actionHide)
return hidePixmap[pn];
else if (fAction == actionRollup)
return getFrame()->isRollup() ? rolldownPixmap[pn] : rollupPixmap[pn];
else if (fAction == actionDepth)
return depthPixmap[pn];
else if (fAction == actionNull &&
LOOK(lookPixmap | lookMetal | lookGtk | lookFlat | lookMotif))
return menuButton[pn];
else
return null;
}
void YFrameButton::paint(Graphics &g, const YRect &/*r*/) {
int xPos = 1, yPos = 1;
int pn = LOOK(lookPixmap | lookMetal | lookGtk | lookFlat)
&& getFrame()->focused() ? 1 : 0;
const bool armed(isArmed());
g.setColor(titleButtonBg);
if (fOver && rolloverTitleButtons) {
if (pn == 1) {
pn = 2;
} else {
pn = 0;
}
}
int iconSize =
YIcon::smallSize();
ref<YIcon> icon =
(fAction == actionNull) ? getFrame()->clientIcon() : null;
ref<YPixmap> pixmap = getPixmap(pn);
if (pixmap == null && pn) {
pixmap = getPixmap(0);
}
if (pixmap != null && pixmap->depth() != g.rdepth()) {
tlog("YFrameButton::%s: attempt to use pixmap 0x%lx of depth %d with gc of depth %d\n",
__func__, pixmap->pixmap(), pixmap->depth(), g.rdepth());
}
if (wmLook == lookWarp4) {
if (fAction == actionNull) {
g.fillRect(0, 0, width(), height());
if (armed)
g.setColor(activeTitleBarBg);
g.fillRect(1, 1, width() - 2, height() - 2);
if (icon != null && showFrameIcon) {
icon->draw(g,
(width() - iconSize) / 2,
(height() - iconSize) / 2,
iconSize);
}
} else {
g.fillRect(0, 0, width(), height());
if (pixmap != null)
g.copyPixmap(pixmap, 0, armed ? 20 : 0,
pixmap->width(), pixmap->height() / 2,
(width() - pixmap->width()) / 2,
(height() - pixmap->height() / 2));
}
}
else if (LOOK(lookMotif | lookWarp3 | lookNice)) {
g.draw3DRect(0, 0, width() - 1, height() - 1, !armed);
if (wmLook != lookMotif) {
if (armed) {
xPos = 3;
yPos = 3;
g.drawLine(1, 1, width() - 2, 1);
g.drawLine(1, 1, 1, height() - 2);
g.drawLine(2, 2, width() - 3, 2);
g.drawLine(2, 2, 2, height() - 3);
} else {
xPos = 2;
yPos = 2;
g.drawRect(1, 1, width() - 3, width() - 3);
}
}
unsigned const w(LOOK(lookMotif) ? width() - 2 : width() - 4);
unsigned const h(LOOK(lookMotif) ? height() - 2 : height() - 4);
if (fAction == actionNull) {
g.fillRect(xPos, yPos, w, h);
if (icon != null && showFrameIcon) {
icon->draw(g,
xPos + (w - iconSize) / 2,
yPos + (h - iconSize) / 2,
iconSize);
}
else if (pixmap != null) {
g.drawCenteredPixmap(xPos, yPos, w, h, pixmap);
}
} else {
if (pixmap != null)
g.drawCenteredPixmap(xPos, yPos, w, h, pixmap);
}
}
else if (wmLook == lookWin95) {
if (fAction == actionNull) {
if (!armed) {
YColor * bg(getFrame()->focused() ? activeTitleBarBg
: inactiveTitleBarBg);
g.setColor(bg);
}
g.fillRect(0, 0, width(), height());
if (icon != null && showFrameIcon) {
icon->draw(g,
(width() - iconSize) / 2,
(height() - iconSize) / 2,
iconSize);
}
} else {
g.drawBorderW(0, 0, width() - 1, height() - 1, !armed);
if (armed)
xPos = yPos = 2;
if (pixmap != null)
g.drawCenteredPixmap(xPos, yPos, width() - 3, height() - 3,
pixmap);
}
}
else if (LOOK(lookPixmap | lookMetal | lookFlat | lookGtk)) {
if (pixmap != null) {
if ( getPixmap(1) != null ) {
int const h(pixmap->height() / 2);
g.copyPixmap(pixmap, 0, armed ? h : 0, pixmap->width(), h, 0, 0);
} else {
// If we have only an image we change
// the over or armed color and paint it.
g.fillRect(0, 0, width(), height());
if (armed)
g.setColor(activeTitleBarBg->darker());
else if (rolloverTitleButtons && fOver)
g.setColor(activeTitleBarBg->brighter());
g.fillRect(1, 1, width()-2, height()-3);
int x(((int)width() - (int)pixmap->width()) / 2);
int y(((int)height() - (int)pixmap->height()) / 2);
g.drawPixmap(pixmap, x, y);
}
}
else {
g.fillRect(0, 0, width(), height());
}
if (fAction == actionNull && icon != null && showFrameIcon) {
icon->draw(g,
((int)width() - (int)iconSize) / 2,
((int)height() - (int)iconSize) / 2,
iconSize);
}
}
}
void YFrameButton::paintFocus(Graphics &/*g*/, const YRect &/*r*/) {
}
// vim: set sw=4 ts=4 et:
<commit_msg>More fixes for unsigned width/height.<commit_after>/*
* IceWM
*
* Copyright (C) 1997-2001 Marko Macek
*/
#include "config.h"
#include "wmbutton.h"
#include "wmframe.h"
#include "wmtitle.h"
#include "yxapp.h"
#include "yicon.h"
#include "yprefs.h"
#include "prefs.h"
#include "wpixmaps.h"
static YColor *titleButtonBg = 0;
static YColor *titleButtonFg = 0;
//!!! get rid of this
extern YColor *activeTitleBarBg;
extern YColor *inactiveTitleBarBg;
YFrameButton::YFrameButton(YWindow *parent,
bool right,
YFrameWindow *frame,
YAction action,
YAction action2):
YButton(desktop, actionNull),
fFrame(frame),
fRight(right),
fAction(action),
fAction2(action2)
{
reparent(parent, 0, 0);
if (titleButtonBg == 0)
titleButtonBg = new YColor(clrNormalTitleButton);
if (titleButtonFg == 0)
titleButtonFg = new YColor(clrNormalTitleButtonText);
if (fAction == actionNull)
setPopup(frame->windowMenu());
if (right)
setWinGravity(NorthEastGravity);
setSize(0,0);
}
YFrameButton::~YFrameButton() {
}
void YFrameButton::handleButton(const XButtonEvent &button) {
if (button.type == ButtonPress &&
(buttonRaiseMask & (1 << (button.button - 1))))
{
if (!(button.state & ControlMask) && raiseOnClickButton) {
getFrame()->activate();
if (raiseOnClickButton && fAction != actionDepth)
getFrame()->wmRaise();
}
}
YButton::handleButton(button);
}
void YFrameButton::handleClick(const XButtonEvent &up, int count) {
if (fAction == actionNull && up.button == 1) {
if ((count % 2) == 0) {
setArmed(false, false);
getFrame()->wmClose();
}
} else if (up.button == 3 && (KEY_MODMASK(up.state) & (xapp->AltMask)) == 0) {
if (!isPopupActive())
getFrame()->popupSystemMenu(this, up.x_root, up.y_root,
YPopupWindow::pfCanFlipVertical |
YPopupWindow::pfCanFlipHorizontal);
}
}
void YFrameButton::handleBeginDrag(const XButtonEvent &down, const XMotionEvent &/*motion*/) {
if (down.button == 3 && getFrame()->canMove()) {
if (!isPopupActive()) {
YFrameTitleBar* tbar = getFrame()->titlebar();
getFrame()->startMoveSize(true, true,
0, 0,
down.x + x() + (tbar ? tbar->x() : 0),
down.y + y() + (tbar ? tbar->y() : 0));
}
}
}
void YFrameButton::setActions(YAction action, YAction action2) {
fAction2 = action2;
if (action != fAction) {
fAction = action;
repaint();
}
}
void YFrameButton::updatePopup() {
getFrame()->updateMenu();
}
void YFrameButton::actionPerformed(YAction /*action*/, unsigned int modifiers) {
if ((modifiers & ShiftMask) && fAction2 != actionNull)
getFrame()->actionPerformed(fAction2, modifiers);
else
getFrame()->actionPerformed(fAction, modifiers);
}
ref<YPixmap> YFrameButton::getPixmap(int pn) const {
if (fAction == actionMaximize)
return maximizePixmap[pn];
else if (fAction == actionMinimize)
return minimizePixmap[pn];
else if (fAction == actionRestore)
return restorePixmap[pn];
else if (fAction == actionClose)
return closePixmap[pn];
else if (fAction == actionHide)
return hidePixmap[pn];
else if (fAction == actionRollup)
return getFrame()->isRollup() ? rolldownPixmap[pn] : rollupPixmap[pn];
else if (fAction == actionDepth)
return depthPixmap[pn];
else if (fAction == actionNull &&
LOOK(lookPixmap | lookMetal | lookGtk | lookFlat | lookMotif))
return menuButton[pn];
else
return null;
}
void YFrameButton::paint(Graphics &g, const YRect &/*r*/) {
int xPos = 1, yPos = 1;
int pn = LOOK(lookPixmap | lookMetal | lookGtk | lookFlat)
&& getFrame()->focused() ? 1 : 0;
const bool armed(isArmed());
g.setColor(titleButtonBg);
if (fOver && rolloverTitleButtons) {
if (pn == 1) {
pn = 2;
} else {
pn = 0;
}
}
int iconSize =
YIcon::smallSize();
ref<YIcon> icon =
(fAction == actionNull) ? getFrame()->clientIcon() : null;
ref<YPixmap> pixmap = getPixmap(pn);
if (pixmap == null && pn) {
pixmap = getPixmap(0);
}
if (pixmap != null && pixmap->depth() != g.rdepth()) {
tlog("YFrameButton::%s: attempt to use pixmap 0x%lx of depth %d with gc of depth %d\n",
__func__, pixmap->pixmap(), pixmap->depth(), g.rdepth());
}
if (wmLook == lookWarp4) {
if (fAction == actionNull) {
g.fillRect(0, 0, width(), height());
if (armed)
g.setColor(activeTitleBarBg);
g.fillRect(1, 1, width() - 2, height() - 2);
if (icon != null && showFrameIcon) {
icon->draw(g,
((int) width() - iconSize) / 2,
((int) height() - iconSize) / 2,
iconSize);
}
} else {
g.fillRect(0, 0, width(), height());
if (pixmap != null)
g.copyPixmap(pixmap, 0, armed ? 20 : 0,
pixmap->width(), pixmap->height() / 2,
((int) width() - (int) pixmap->width()) / 2,
((int) height() - (int) pixmap->height() / 2));
}
}
else if (LOOK(lookMotif | lookWarp3 | lookNice)) {
g.draw3DRect(0, 0, width() - 1, height() - 1, !armed);
if (wmLook != lookMotif) {
if (armed) {
xPos = 3;
yPos = 3;
g.drawLine(1, 1, width() - 2, 1);
g.drawLine(1, 1, 1, height() - 2);
g.drawLine(2, 2, width() - 3, 2);
g.drawLine(2, 2, 2, height() - 3);
} else {
xPos = 2;
yPos = 2;
g.drawRect(1, 1, width() - 3, width() - 3);
}
}
unsigned const w(LOOK(lookMotif) ? width() - 2 : width() - 4);
unsigned const h(LOOK(lookMotif) ? height() - 2 : height() - 4);
if (fAction == actionNull) {
g.fillRect(xPos, yPos, w, h);
if (icon != null && showFrameIcon) {
icon->draw(g,
xPos + ((int) w - iconSize) / 2,
yPos + ((int) h - iconSize) / 2,
iconSize);
}
else if (pixmap != null) {
g.drawCenteredPixmap(xPos, yPos, w, h, pixmap);
}
} else {
if (pixmap != null)
g.drawCenteredPixmap(xPos, yPos, w, h, pixmap);
}
}
else if (wmLook == lookWin95) {
if (fAction == actionNull) {
if (!armed) {
YColor * bg(getFrame()->focused() ? activeTitleBarBg
: inactiveTitleBarBg);
g.setColor(bg);
}
g.fillRect(0, 0, width(), height());
if (icon != null && showFrameIcon) {
icon->draw(g,
((int) width() - iconSize) / 2,
((int) height() - iconSize) / 2,
iconSize);
}
} else {
g.drawBorderW(0, 0, width() - 1, height() - 1, !armed);
if (armed)
xPos = yPos = 2;
if (pixmap != null)
g.drawCenteredPixmap(xPos, yPos, width() - 3, height() - 3,
pixmap);
}
}
else if (LOOK(lookPixmap | lookMetal | lookFlat | lookGtk)) {
if (pixmap != null) {
if ( getPixmap(1) != null ) {
int const h(pixmap->height() / 2);
g.copyPixmap(pixmap, 0, armed ? h : 0, pixmap->width(), h, 0, 0);
} else {
// If we have only an image we change
// the over or armed color and paint it.
g.fillRect(0, 0, width(), height());
if (armed)
g.setColor(activeTitleBarBg->darker());
else if (rolloverTitleButtons && fOver)
g.setColor(activeTitleBarBg->brighter());
g.fillRect(1, 1, width()-2, height()-3);
int x(((int)width() - (int)pixmap->width()) / 2);
int y(((int)height() - (int)pixmap->height()) / 2);
g.drawPixmap(pixmap, x, y);
}
}
else {
g.fillRect(0, 0, width(), height());
}
if (fAction == actionNull && icon != null && showFrameIcon) {
icon->draw(g,
((int)width() - (int)iconSize) / 2,
((int)height() - (int)iconSize) / 2,
iconSize);
}
}
}
void YFrameButton::paintFocus(Graphics &/*g*/, const YRect &/*r*/) {
}
// vim: set sw=4 ts=4 et:
<|endoftext|>
|
<commit_before>/*
* IceWM
*
* Copyright (C) 1997-2002 Marko Macek
*/
#include "config.h"
#include "ykey.h"
#include "ylib.h"
#include "yprefs.h"
#define CFGDEF
#include "wmconfig.h"
#include "bindkey.h"
#include "default.h"
#include "wmoption.h"
#include "wmmgr.h"
#include "yaction.h"
#include "yapp.h"
#include "sysdep.h"
#include "intl.h"
long workspaceCount = 0;
char *workspaceNames[MAXWORKSPACES];
YAction *workspaceActionActivate[MAXWORKSPACES];
YAction *workspaceActionMoveTo[MAXWORKSPACES];
void WMConfig::loadConfiguration(IApp *app, const char *fileName) {
#ifndef NO_CONFIGURE
YConfig::findLoadConfigFile(app, icewm_preferences, fileName);
YConfig::findLoadConfigFile(app, icewm_themable_preferences, fileName);
#endif
}
void WMConfig::loadThemeConfiguration(IApp *app, const char *themeName) {
#ifndef NO_CONFIGURE
bool ok = YConfig::findLoadThemeFile(app,
icewm_themable_preferences,
upath("themes").child(themeName));
if (ok == false)
fail(_("Failed to load theme %s"), themeName);
#endif
}
void WMConfig::freeConfiguration() {
#ifndef NO_CONFIGURE
YConfig::freeConfig(icewm_preferences);
#endif
}
void addWorkspace(const char * /*name*/, const char *value, bool append) {
if (!append) {
for (int i = 0; i < workspaceCount; i++) {
delete[] workspaceNames[i];
delete workspaceActionActivate[i];
delete workspaceActionMoveTo[i];
}
workspaceCount = 0;
}
if (workspaceCount >= MAXWORKSPACES)
return;
workspaceNames[workspaceCount] = newstr(value);
workspaceActionActivate[workspaceCount] = new YAction(); // !! fix
workspaceActionMoveTo[workspaceCount] = new YAction();
PRECONDITION(workspaceNames[workspaceCount] != NULL);
workspaceCount++;
}
static const struct {
const char name[8];
enum WMLook value;
} wmLookNames[] = {
{ "win95", lookWin95 },
{ "motif", lookMotif },
{ "warp3", lookWarp3 },
{ "warp4", lookWarp4 },
{ "nice", lookNice },
{ "pixmap", lookPixmap },
{ "metal", lookMetal },
{ "gtk", lookGtk },
{ "flat", lookFlat },
};
const char* getLookName(enum WMLook look) {
for (size_t k = 0; k < ACOUNT(wmLookNames); ++k) {
if (look == wmLookNames[k].value)
return wmLookNames[k].name;
}
return "";
}
bool getLook(const char *name, const char *arg, enum WMLook *lookPtr) {
for (size_t k = 0; k < ACOUNT(wmLookNames); ++k) {
if (0 == strcmp(arg, wmLookNames[k].name)) {
if (lookPtr) {
*lookPtr = wmLookNames[k].value;
}
return true;
}
}
return false;
}
#ifndef NO_CONFIGURE
void setLook(const char *name, const char *arg, bool) {
enum WMLook look = wmLook;
if (getLook(name, arg, &look)) {
wmLook = look;
} else {
msg(_("Unknown value '%s' for option '%s'."), arg, name);
}
}
#endif
static bool ensureDirectory(const upath& path) {
if (path.dirExists())
return true;
if (path.mkdir() != 0) {
fail(_("Unable to create directory %s"), path.string().c_str());
}
return path.dirExists();
}
static upath getDefaultsFilePath(const pstring& basename) {
upath xdg(YApplication::getXdgConfDir());
if (xdg.dirExists()) {
upath file(xdg + basename);
if (file.fileExists())
return file;
}
upath prv(YApplication::getPrivConfDir());
if (ensureDirectory(prv)) {
return prv + basename;
}
ensureDirectory(xdg.parent());
if (ensureDirectory(xdg)) {
return xdg + basename;
}
return null;
}
int WMConfig::setDefault(const char *basename, const char *content) {
upath confOld(getDefaultsFilePath(basename));
if (confOld == null) {
return -1; // no directory
}
upath confNew(confOld.path() + ".new.tmp");
FILE *fpNew = confNew.fopen("w");
if (fpNew) {
fputs(content, fpNew);
if (content[0] && content[strlen(content)-1] != '\n')
fputc('\n', fpNew);
}
if (fpNew == NULL || fflush(fpNew) || ferror(fpNew)) {
fail(_("Unable to write to %s"), confNew.string().c_str());
if (fpNew)
fclose(fpNew);
confNew.remove();
return -1;
}
FILE *fpOld = confOld.fopen("r");
if (fpOld) {
for (int i = 0; i < 10; ++i) {
char buf[600] = "#", *line = buf;
if (fgets(1 + buf, sizeof buf - 1, fpOld)) {
while (line[1] == '#')
++line;
fputs(line, fpNew);
if ('\n' != line[strlen(line)-1])
fputc('\n', fpNew);
}
}
fclose(fpOld);
}
fclose(fpNew);
if (fpOld != 0 || confOld.access() == 0) {
confOld.remove();
}
if (confNew.renameAs(confOld)) {
fail(_("Unable to rename %s to %s"),
confNew.string().c_str(), confOld.string().c_str());
confNew.remove();
}
return 0;
}
static void print_options(cfoption *options) {
for (int i = 0; options[i].type != cfoption::CF_NONE; ++i) {
if (options[i].notify) {
if (0 == strcmp("Look", options[i].name)) {
printf("%s=%s\n", "Look", getLookName(wmLook));
}
continue;
}
switch (options[i].type) {
case cfoption::CF_BOOL:
printf("%s=%d\n", options[i].name, *options[i].v.bool_value);
break;
case cfoption::CF_INT:
printf("%s=%d\n", options[i].name, *options[i].v.i.int_value);
break;
case cfoption::CF_STR:
printf("%s=\"%s\"\n", options[i].name,
options[i].v.s.string_value && *options[i].v.s.string_value
? *options[i].v.s.string_value : "");
break;
#ifndef NO_KEYBIND
case cfoption::CF_KEY:
printf("%s=\"%s\"\n", options[i].name,
options[i].v.k.key_value->name);
break;
#endif
case cfoption::CF_NONE:
break;
}
}
}
void WMConfig::print_preferences() {
#ifndef NO_CONFIGURE
print_options(icewm_preferences);
print_options(icewm_themable_preferences);
#endif
}
<commit_msg>Free theme_preferences when done.<commit_after>/*
* IceWM
*
* Copyright (C) 1997-2002 Marko Macek
*/
#include "config.h"
#include "ykey.h"
#include "ylib.h"
#include "yprefs.h"
#define CFGDEF
#include "wmconfig.h"
#include "bindkey.h"
#include "default.h"
#include "wmoption.h"
#include "wmmgr.h"
#include "yaction.h"
#include "yapp.h"
#include "sysdep.h"
#include "intl.h"
long workspaceCount = 0;
char *workspaceNames[MAXWORKSPACES];
YAction *workspaceActionActivate[MAXWORKSPACES];
YAction *workspaceActionMoveTo[MAXWORKSPACES];
void WMConfig::loadConfiguration(IApp *app, const char *fileName) {
#ifndef NO_CONFIGURE
YConfig::findLoadConfigFile(app, icewm_preferences, fileName);
YConfig::findLoadConfigFile(app, icewm_themable_preferences, fileName);
#endif
}
void WMConfig::loadThemeConfiguration(IApp *app, const char *themeName) {
#ifndef NO_CONFIGURE
bool ok = YConfig::findLoadThemeFile(app,
icewm_themable_preferences,
upath("themes").child(themeName));
if (ok == false)
fail(_("Failed to load theme %s"), themeName);
#endif
}
void WMConfig::freeConfiguration() {
#ifndef NO_CONFIGURE
YConfig::freeConfig(icewm_preferences);
YConfig::freeConfig(icewm_themable_preferences);
#endif
}
void addWorkspace(const char * /*name*/, const char *value, bool append) {
if (!append) {
for (int i = 0; i < workspaceCount; i++) {
delete[] workspaceNames[i];
delete workspaceActionActivate[i];
delete workspaceActionMoveTo[i];
}
workspaceCount = 0;
}
if (workspaceCount >= MAXWORKSPACES)
return;
workspaceNames[workspaceCount] = newstr(value);
workspaceActionActivate[workspaceCount] = new YAction(); // !! fix
workspaceActionMoveTo[workspaceCount] = new YAction();
PRECONDITION(workspaceNames[workspaceCount] != NULL);
workspaceCount++;
}
static const struct {
const char name[8];
enum WMLook value;
} wmLookNames[] = {
{ "win95", lookWin95 },
{ "motif", lookMotif },
{ "warp3", lookWarp3 },
{ "warp4", lookWarp4 },
{ "nice", lookNice },
{ "pixmap", lookPixmap },
{ "metal", lookMetal },
{ "gtk", lookGtk },
{ "flat", lookFlat },
};
const char* getLookName(enum WMLook look) {
for (size_t k = 0; k < ACOUNT(wmLookNames); ++k) {
if (look == wmLookNames[k].value)
return wmLookNames[k].name;
}
return "";
}
bool getLook(const char *name, const char *arg, enum WMLook *lookPtr) {
for (size_t k = 0; k < ACOUNT(wmLookNames); ++k) {
if (0 == strcmp(arg, wmLookNames[k].name)) {
if (lookPtr) {
*lookPtr = wmLookNames[k].value;
}
return true;
}
}
return false;
}
#ifndef NO_CONFIGURE
void setLook(const char *name, const char *arg, bool) {
enum WMLook look = wmLook;
if (getLook(name, arg, &look)) {
wmLook = look;
} else {
msg(_("Unknown value '%s' for option '%s'."), arg, name);
}
}
#endif
static bool ensureDirectory(const upath& path) {
if (path.dirExists())
return true;
if (path.mkdir() != 0) {
fail(_("Unable to create directory %s"), path.string().c_str());
}
return path.dirExists();
}
static upath getDefaultsFilePath(const pstring& basename) {
upath xdg(YApplication::getXdgConfDir());
if (xdg.dirExists()) {
upath file(xdg + basename);
if (file.fileExists())
return file;
}
upath prv(YApplication::getPrivConfDir());
if (ensureDirectory(prv)) {
return prv + basename;
}
ensureDirectory(xdg.parent());
if (ensureDirectory(xdg)) {
return xdg + basename;
}
return null;
}
int WMConfig::setDefault(const char *basename, const char *content) {
upath confOld(getDefaultsFilePath(basename));
if (confOld == null) {
return -1; // no directory
}
upath confNew(confOld.path() + ".new.tmp");
FILE *fpNew = confNew.fopen("w");
if (fpNew) {
fputs(content, fpNew);
if (content[0] && content[strlen(content)-1] != '\n')
fputc('\n', fpNew);
}
if (fpNew == NULL || fflush(fpNew) || ferror(fpNew)) {
fail(_("Unable to write to %s"), confNew.string().c_str());
if (fpNew)
fclose(fpNew);
confNew.remove();
return -1;
}
FILE *fpOld = confOld.fopen("r");
if (fpOld) {
for (int i = 0; i < 10; ++i) {
char buf[600] = "#", *line = buf;
if (fgets(1 + buf, sizeof buf - 1, fpOld)) {
while (line[1] == '#')
++line;
fputs(line, fpNew);
if ('\n' != line[strlen(line)-1])
fputc('\n', fpNew);
}
}
fclose(fpOld);
}
fclose(fpNew);
if (fpOld != 0 || confOld.access() == 0) {
confOld.remove();
}
if (confNew.renameAs(confOld)) {
fail(_("Unable to rename %s to %s"),
confNew.string().c_str(), confOld.string().c_str());
confNew.remove();
}
return 0;
}
static void print_options(cfoption *options) {
for (int i = 0; options[i].type != cfoption::CF_NONE; ++i) {
if (options[i].notify) {
if (0 == strcmp("Look", options[i].name)) {
printf("%s=%s\n", "Look", getLookName(wmLook));
}
continue;
}
switch (options[i].type) {
case cfoption::CF_BOOL:
printf("%s=%d\n", options[i].name, *options[i].v.bool_value);
break;
case cfoption::CF_INT:
printf("%s=%d\n", options[i].name, *options[i].v.i.int_value);
break;
case cfoption::CF_STR:
printf("%s=\"%s\"\n", options[i].name,
options[i].v.s.string_value && *options[i].v.s.string_value
? *options[i].v.s.string_value : "");
break;
#ifndef NO_KEYBIND
case cfoption::CF_KEY:
printf("%s=\"%s\"\n", options[i].name,
options[i].v.k.key_value->name);
break;
#endif
case cfoption::CF_NONE:
break;
}
}
}
void WMConfig::print_preferences() {
#ifndef NO_CONFIGURE
print_options(icewm_preferences);
print_options(icewm_themable_preferences);
#endif
}
<|endoftext|>
|
<commit_before>// This file was copied from dune-fem and slightly modified.
// See http://dune.mathematik.uni-freiburg.de/ for the orginal
// file, authors, licence and readme!
#ifndef DUNE_GRID_PART_INDEXSET_DEFAULT_HH
#define DUNE_GRID_PART_INDEXSET_DEFAULT_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG
// system
#include <vector>
#include <rpc/rpc.h>
// dune-common
#include <dune/common/misc.hh>
#include <dune/common/typetraits.hh>
#include <dune/common/version.hh>
// dune-grid
#include <dune/grid/common/grid.hh>
//#include <dune/grid/common/adaptcallback.hh> // for compatibility only
// dune-grid-multiscale
#include <dune/grid/part/indexset/empty.hh>
//#include <dune/fem/misc/capabilities.hh>
//#include <dune/fem/misc/mpimanager.hh>
namespace Dune {
namespace grid {
namespace Part {
namespace IndexSet {
namespace Default {
//! Wraps the interface methods of indexsets and adds the addiotnal needed
//! functions
template <class IndexSetImp >
class Wrapper : public Empty
{
public:
typedef typename IndexSetImp :: IndexType IndexType ;
//! The types of the iterator
template<int cd>
struct Codim
{
template<PartitionIteratorType pitype>
struct Partition
{
typedef typename IndexSetImp::template Codim<cd>::
template Partition<pitype>::Iterator Iterator;
};
};
//! store const reference to set
Wrapper(const IndexSetImp & set, bool /*adaptive*/ = false)
: Empty()
, set_(set)
{}
//! store const reference to set
Wrapper(const Wrapper<IndexSetImp> & s)
: Empty(/*s.adaptive_*/),
set_(s.set_)
{}
//! return persistent status
bool persistent () const { return false; }
//! return size of set for codim
int size ( GeometryType type ) const
{
return set_.size(type);
}
//! return size of grid entities per level and codim
int size ( int codim ) const
{
return set_.size(codim);
}
//! return index of en
template <class EntityType>
int index (const EntityType & en) const
{
return set_.index(en);
}
//! return sub index of given entities sub entity with codim and number
template< int codim, class EntityType >
int DUNE_DEPRECATED subIndex ( const EntityType &entity, int num ) const
{
return set_.template subIndex< codim >( entity, num );
}
template< class Entity >
int subIndex ( const Entity &entity, int num, unsigned int codim ) const
{
return set_.subIndex( entity, num, codim );
}
//! wrap geomTypes method of set
const std::vector< GeometryType > & geomTypes (int codim) const
{
return set_.geomTypes(codim);
}
//! returns true if this set provides an index for given entity
template<class EntityType>
bool contains (const EntityType& en) const
{
return set_.contains(en);
}
//! return index
template< int codim, class Entity >
int DUNE_DEPRECATED index ( const Entity &entity, int i ) const
{
static const int DUNE_UNUSED(cc) = Entity::codimension;
return set_.subIndex( entity, i, codim );
}
/** @brief Iterator to first entity of given codimension and partition type.
*/
template<int cd, PartitionIteratorType pitype>
typename Codim<cd>::template Partition<pitype>::Iterator begin () const
{
return set_.template begin<cd,pitype> ();
}
/** @brief Iterator to one past the last entity of given codim for partition type
*/
template<int cd, PartitionIteratorType pitype>
typename Codim<cd>::template Partition<pitype>::Iterator end () const
{
return set_.template end<cd,pitype> ();
}
private:
const IndexSetImp & set_;
}; // class Wrapper
//! Wraps LeafIndexSet of Dune Grids for use with LagrangeFunctionSpace
template <class GridType>
class Leaf
: public Wrapper<typename GridType :: Traits :: LeafIndexSet>
{
// my type, to be revised
enum { myType = 5 };
// my index set type
typedef typename GridType :: Traits :: LeafIndexSet IndexSetType;
typedef Leaf<GridType> ThisType;
public:
//! number of codimensions
enum { ncodim = GridType::dimension + 1 };
//! constructor
Leaf ( const GridType & grid , const int /*level*/ =-1 )
: Wrapper < IndexSetType > (grid.leafIndexSet()) {}
//! constructor taking grid part
template <class GridPartType>
Leaf ( const GridPartType& gridPart )
: Wrapper < IndexSetType > (gridPart.grid().leafIndexSet()) {}
//! return type (for Grape In/Output)
static int type() { return myType; }
//! returns reference to singleton
static ThisType & instance (const GridType & grid)
{
static ThisType set(grid,grid.maxLevel());
return set;
}
}; // class Leaf
} // namespace Default
} // namespace IndexSet
} // namespace Part
} // namespace grid
} // namespace Dune
#endif // DUNE_GRID_PART_INDEXSET_DEFAULT_HH
<commit_msg>[indexset.default] add another index() to please dune-pdelab<commit_after>// This file was copied from dune-fem and slightly modified.
// See http://dune.mathematik.uni-freiburg.de/ for the orginal
// file, authors, licence and readme!
#ifndef DUNE_GRID_PART_INDEXSET_DEFAULT_HH
#define DUNE_GRID_PART_INDEXSET_DEFAULT_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG
// system
#include <vector>
#include <rpc/rpc.h>
// dune-common
#include <dune/common/misc.hh>
#include <dune/common/typetraits.hh>
#include <dune/common/version.hh>
// dune-grid
#include <dune/grid/common/grid.hh>
//#include <dune/grid/common/adaptcallback.hh> // for compatibility only
// dune-grid-multiscale
#include <dune/grid/part/indexset/empty.hh>
//#include <dune/fem/misc/capabilities.hh>
//#include <dune/fem/misc/mpimanager.hh>
namespace Dune {
namespace grid {
namespace Part {
namespace IndexSet {
namespace Default {
//! Wraps the interface methods of indexsets and adds the addiotnal needed
//! functions
template <class IndexSetImp >
class Wrapper : public Empty
{
public:
typedef typename IndexSetImp :: IndexType IndexType ;
//! The types of the iterator
template<int cd>
struct Codim
{
template<PartitionIteratorType pitype>
struct Partition
{
typedef typename IndexSetImp::template Codim<cd>::
template Partition<pitype>::Iterator Iterator;
};
};
//! store const reference to set
Wrapper(const IndexSetImp & set, bool /*adaptive*/ = false)
: Empty()
, set_(set)
{}
//! store const reference to set
Wrapper(const Wrapper<IndexSetImp> & s)
: Empty(/*s.adaptive_*/),
set_(s.set_)
{}
//! return persistent status
bool persistent () const { return false; }
//! return size of set for codim
int size ( GeometryType type ) const
{
return set_.size(type);
}
//! return size of grid entities per level and codim
int size ( int codim ) const
{
return set_.size(codim);
}
//! return index of en
template <class EntityType>
int index (const EntityType & en) const
{
return set_.index(en);
}
//! return index of en
template< int cc, class EntityType >
int index(const EntityType & en) const
{
return set_.index(en);
}
//! return sub index of given entities sub entity with codim and number
template< int codim, class EntityType >
int DUNE_DEPRECATED subIndex ( const EntityType &entity, int num ) const
{
return set_.template subIndex< codim >( entity, num );
}
template< class Entity >
int subIndex ( const Entity &entity, int num, unsigned int codim ) const
{
return set_.subIndex( entity, num, codim );
}
//! wrap geomTypes method of set
const std::vector< GeometryType > & geomTypes (int codim) const
{
return set_.geomTypes(codim);
}
//! returns true if this set provides an index for given entity
template<class EntityType>
bool contains (const EntityType& en) const
{
return set_.contains(en);
}
//! return index
template< int codim, class Entity >
int DUNE_DEPRECATED index ( const Entity &entity, int i ) const
{
static const int DUNE_UNUSED(cc) = Entity::codimension;
return set_.subIndex( entity, i, codim );
}
/** @brief Iterator to first entity of given codimension and partition type.
*/
template<int cd, PartitionIteratorType pitype>
typename Codim<cd>::template Partition<pitype>::Iterator begin () const
{
return set_.template begin<cd,pitype> ();
}
/** @brief Iterator to one past the last entity of given codim for partition type
*/
template<int cd, PartitionIteratorType pitype>
typename Codim<cd>::template Partition<pitype>::Iterator end () const
{
return set_.template end<cd,pitype> ();
}
private:
const IndexSetImp & set_;
}; // class Wrapper
//! Wraps LeafIndexSet of Dune Grids for use with LagrangeFunctionSpace
template <class GridType>
class Leaf
: public Wrapper<typename GridType :: Traits :: LeafIndexSet>
{
// my type, to be revised
enum { myType = 5 };
// my index set type
typedef typename GridType :: Traits :: LeafIndexSet IndexSetType;
typedef Leaf<GridType> ThisType;
public:
//! number of codimensions
enum { ncodim = GridType::dimension + 1 };
//! constructor
Leaf ( const GridType & grid , const int /*level*/ =-1 )
: Wrapper < IndexSetType > (grid.leafIndexSet()) {}
//! constructor taking grid part
template <class GridPartType>
Leaf ( const GridPartType& gridPart )
: Wrapper < IndexSetType > (gridPart.grid().leafIndexSet()) {}
//! return type (for Grape In/Output)
static int type() { return myType; }
//! returns reference to singleton
static ThisType & instance (const GridType & grid)
{
static ThisType set(grid,grid.maxLevel());
return set;
}
}; // class Leaf
} // namespace Default
} // namespace IndexSet
} // namespace Part
} // namespace grid
} // namespace Dune
#endif // DUNE_GRID_PART_INDEXSET_DEFAULT_HH
<|endoftext|>
|
<commit_before>#include <config.h>
#include <dune/common/exceptions.hh>
#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/parallel/collectivecommunication.hh>
#include <dune/stuff/common/validation.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/multiscale/problems/selector.hh>
#include <math.h>
#include <sstream>
#include <mpi.h>
#include "dune/multiscale/problems/base.hh"
#include "random.hh"
#if HAVE_RANDOM_PROBLEM
#include "random_permeability.hh"
#endif
namespace Dune {
namespace Multiscale {
namespace Problem {
namespace Random {
ModelProblemData::ModelProblemData()
: IModelProblemData()
, boundaryInfo_(DSG::BoundaryInfos::NormalBased<typename View::Intersection>::create(boundary_settings()))
, subBoundaryInfo_() {}
// functions actually unused
std::string ModelProblemData::getMacroGridFile() const { return ""; }
std::pair<CommonTraits::DomainType, CommonTraits::DomainType> ModelProblemData::gridCorners() const {
CommonTraits::DomainType lowerLeft(0.0);
CommonTraits::DomainType upperRight(1.0);
return {lowerLeft, upperRight};
}
void ModelProblemData::problem_init(DMP::ProblemContainer& problem, MPIHelper::MPICommunicator global,
MPIHelper::MPICommunicator local) {
problem.getMutableDiffusion().init(problem, global, local);
}
void ModelProblemData::prepare_new_evaluation(DMP::ProblemContainer& problem) {
problem.getMutableDiffusion().prepare_new_evaluation();
}
void Diffusion::init(const DMP::ProblemContainer& problem, MPIHelper::MPICommunicator global,
MPIHelper::MPICommunicator local) {
const auto cells_per_dim = problem.config().get<std::vector<std::size_t>>("grids.macro_cells_per_dim");
std::for_each(cells_per_dim.begin(), cells_per_dim.end(), [&](size_t t) { assert(t == cells_per_dim[0]); });
const int log2Seg = std::log2l(cells_per_dim[0]);
int seed = 0;
MPI_Comm_rank(global, &seed);
assert(seed >= 0);
const int overlap = problem.config().get("grids.overlap", 1u);
const auto corrLen = problem.config().get("mlmc.correlation_length", 0.2f);
const auto sigma = problem.config().get("mlmc.correlation_sigma", 1.0f);
correlation_ = DSC::make_unique<Correlation>(corrLen, sigma);
DSC::ScopedTiming field_tm("msfem.perm_field.init");
#if HAVE_RANDOM_PROBLEM
field_ = DSC::make_unique<PermeabilityType>(local, *correlation_, log2Seg, seed + 1, overlap);
#else
DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}
void Diffusion::prepare_new_evaluation() {
DSC::ScopedTiming field_tm("msfem.perm_field.create");
#if HAVE_RANDOM_PROBLEM
assert(field_);
field_->create();
#else
DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}
const ModelProblemData::BoundaryInfoType& ModelProblemData::boundaryInfo() const { return *boundaryInfo_; }
const ModelProblemData::SubBoundaryInfoType& ModelProblemData::subBoundaryInfo() const { return subBoundaryInfo_; }
ParameterTree ModelProblemData::boundary_settings() const {
Dune::ParameterTree boundarySettings;
if (DSC_CONFIG.has_sub("problem.boundaryInfo")) {
boundarySettings = DSC_CONFIG.sub("problem.boundaryInfo");
} else {
boundarySettings["default"] = "dirichlet";
boundarySettings["compare_tolerance"] = "1e-10";
switch (CommonTraits::world_dim) {
case 1:
DUNE_THROW(InvalidStateException, "no boundary settings for 1D random field problem");
case 3:
boundarySettings["neumann.0"] = "[0.0 1.0 0.0]";
boundarySettings["neumann.1"] = "[0.0 -1.0 0.0]";
boundarySettings["neumann.2"] = "[0.0 0.0 1.0]";
boundarySettings["neumann.3"] = "[0.0 0.0 -1.0]";
break;
case 2:
boundarySettings["neumann.0"] = "[0.0 1.0]";
boundarySettings["neumann.1"] = "[0.0 -1.0]";
break;
}
}
return boundarySettings;
}
Diffusion::Diffusion() {}
void Diffusion::evaluate(const DomainType& x, Diffusion::RangeType& ret) const {
#if HAVE_RANDOM_PROBLEM
assert(field_);
const double scalar = field_->operator()(x);
ret[0][0] = 1 * scalar;
ret[1][1] = ret[0][0];
#else
DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}
PURE HOT void Diffusion::diffusiveFlux(const DomainType& x, const Problem::JacobianRangeType& direction,
Problem::JacobianRangeType& flux) const {
Diffusion::RangeType eval;
evaluate(x, eval);
flux[0][0] = eval[0][0] * direction[0][0];
flux[0][1] = eval[1][1] * direction[0][1];
} // diffusiveFlux
size_t Diffusion::order() const { return 1; }
PURE void DirichletData::evaluate(const DomainType& x, RangeType& y) const { y = 1.0 - x[0]; } // evaluate
PURE void NeumannData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.; } // evaluate
} // namespace Nine
} // namespace Problem
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>fixes random perm eval in 3D<commit_after>#include <config.h>
#include <dune/common/exceptions.hh>
#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/parallel/collectivecommunication.hh>
#include <dune/stuff/common/validation.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/multiscale/problems/selector.hh>
#include <math.h>
#include <sstream>
#include <mpi.h>
#include "dune/multiscale/problems/base.hh"
#include "random.hh"
#if HAVE_RANDOM_PROBLEM
#include "random_permeability.hh"
#endif
namespace Dune {
namespace Multiscale {
namespace Problem {
namespace Random {
ModelProblemData::ModelProblemData()
: IModelProblemData()
, boundaryInfo_(DSG::BoundaryInfos::NormalBased<typename View::Intersection>::create(boundary_settings()))
, subBoundaryInfo_() {}
// functions actually unused
std::string ModelProblemData::getMacroGridFile() const { return ""; }
std::pair<CommonTraits::DomainType, CommonTraits::DomainType> ModelProblemData::gridCorners() const {
CommonTraits::DomainType lowerLeft(0.0);
CommonTraits::DomainType upperRight(1.0);
return {lowerLeft, upperRight};
}
void ModelProblemData::problem_init(DMP::ProblemContainer& problem, MPIHelper::MPICommunicator global,
MPIHelper::MPICommunicator local) {
problem.getMutableDiffusion().init(problem, global, local);
}
void ModelProblemData::prepare_new_evaluation(DMP::ProblemContainer& problem) {
problem.getMutableDiffusion().prepare_new_evaluation();
}
void Diffusion::init(const DMP::ProblemContainer& problem, MPIHelper::MPICommunicator global,
MPIHelper::MPICommunicator local) {
const auto cells_per_dim = problem.config().get<std::vector<std::size_t>>("grids.macro_cells_per_dim");
std::for_each(cells_per_dim.begin(), cells_per_dim.end(), [&](size_t t) { assert(t == cells_per_dim[0]); });
const int log2Seg = std::log2l(cells_per_dim[0]);
int seed = 0;
MPI_Comm_rank(global, &seed);
assert(seed >= 0);
const int overlap = problem.config().get("grids.overlap", 1u);
const auto corrLen = problem.config().get("mlmc.correlation_length", 0.2f);
const auto sigma = problem.config().get("mlmc.correlation_sigma", 1.0f);
correlation_ = DSC::make_unique<Correlation>(corrLen, sigma);
DSC::ScopedTiming field_tm("msfem.perm_field.init");
#if HAVE_RANDOM_PROBLEM
field_ = DSC::make_unique<PermeabilityType>(local, *correlation_, log2Seg, seed + 1, overlap);
#else
DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}
void Diffusion::prepare_new_evaluation() {
DSC::ScopedTiming field_tm("msfem.perm_field.create");
#if HAVE_RANDOM_PROBLEM
assert(field_);
field_->create();
#else
DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}
const ModelProblemData::BoundaryInfoType& ModelProblemData::boundaryInfo() const { return *boundaryInfo_; }
const ModelProblemData::SubBoundaryInfoType& ModelProblemData::subBoundaryInfo() const { return subBoundaryInfo_; }
ParameterTree ModelProblemData::boundary_settings() const {
Dune::ParameterTree boundarySettings;
if (DSC_CONFIG.has_sub("problem.boundaryInfo")) {
boundarySettings = DSC_CONFIG.sub("problem.boundaryInfo");
} else {
boundarySettings["default"] = "dirichlet";
boundarySettings["compare_tolerance"] = "1e-10";
switch (CommonTraits::world_dim) {
case 1:
DUNE_THROW(InvalidStateException, "no boundary settings for 1D random field problem");
case 3:
boundarySettings["neumann.0"] = "[0.0 1.0 0.0]";
boundarySettings["neumann.1"] = "[0.0 -1.0 0.0]";
boundarySettings["neumann.2"] = "[0.0 0.0 1.0]";
boundarySettings["neumann.3"] = "[0.0 0.0 -1.0]";
break;
case 2:
boundarySettings["neumann.0"] = "[0.0 1.0]";
boundarySettings["neumann.1"] = "[0.0 -1.0]";
break;
}
}
return boundarySettings;
}
Diffusion::Diffusion() {}
void Diffusion::evaluate(const DomainType& x, Diffusion::RangeType& ret) const {
#if HAVE_RANDOM_PROBLEM
assert(field_);
const double scalar = field_->operator()(x);
ret = 0;
for(const auto i : DSC::valueRange(CommonTraits::world_dim))
ret[i][i] = scalar;
#else
DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}
PURE HOT void Diffusion::diffusiveFlux(const DomainType& x, const Problem::JacobianRangeType& direction,
Problem::JacobianRangeType& flux) const {
Diffusion::RangeType eval;
evaluate(x, eval);
flux = 0;
for(const auto i : DSC::valueRange(CommonTraits::world_dim))
flux[0][i] = eval[i][i] * direction[0][i];
} // diffusiveFlux
size_t Diffusion::order() const { return 1; }
PURE void DirichletData::evaluate(const DomainType& x, RangeType& y) const { y = 1.0 - x[0]; } // evaluate
PURE void NeumannData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.; } // evaluate
} // namespace Nine
} // namespace Problem
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|>
|
<commit_before>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
#define DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
#include <dune/common/fmatrix.hh>
#include <dune/common/fvector.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include <dune/pymor/common/exceptions.hh>
namespace Dune {
namespace Pymor {
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class ParametricFunctionInterface
: public Parametric
{
public:
typedef DomainFieldImp DomainFieldType;
static const unsigned int dimDomain = domainDim;
typedef Dune::FieldVector< DomainFieldType, > DomainType;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRangeRows = rangeDimRows;
static const unsigned int dimRangeCols = rangeDimCols;
typedef Dune::FieldMatrix< RangeFieldType, dimRangeRows, dimRangeCols > RangeType;
static const std::string static_id()
{
return "parametricfunction";
}
virtual std::string id() const
{
return static_id();
}
virtual int order() const
{
return -1;
}
virtual evaluate(const DomainType& x, RangeType& ret, const Parameter mu = Parameter()) const = 0;
virtual RangeType evaluate(const DomainType& x, const Parameter mu = Parameter()) const
{
if (mu.type() != Parametric::parameter_type())
DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
"type of mu (" << mu.type() << ") does not match the parameter_type of this ("
<< Parametric::parameter_type() << ")!");
RangeType ret;
evaluate(x, ret, mu);
return ret;
}
}; // class ParametricFunctionInterface
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows >
class ParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, 1 >
: public Parametric
{
public:
typedef DomainFieldImp DomainFieldType;
static const unsigned int dimDomain = domainDim;
typedef Dune::FieldVector< DomainFieldType, > DomainType;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRangeRows = rangeDimRows;
static const unsigned int dimRangeCols = 1;
static const unsigned int dimRange = 1;
typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;
template< class... Args >
ParametricFunctionInterface(Args&& ...args)
: Parametric(std::forward< Args >(args)...)
{}
static const std::string static_id()
{
return "parametricfunction";
}
virtual std::string id() const
{
return static_id();
}
virtual int order() const
{
return -1;
}
virtual evaluate(const DomainType& x, RangeType& ret, const Parameter mu = Parameter()) const = 0;
virtual RangeType evaluate(const DomainType& x, const Parameter mu = Parameter()) const
{
if (mu.type() != Parametric::parameter_type())
DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
"type of mu (" << mu.type() << ") does not match the parameter_type of this ("
<< Parametric::parameter_type() << ")!");
RangeType ret;
evaluate(x, ret, mu);
return ret;
}
}; // class ParametricFunctionInterface< ..., 1 >
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class AffineParametricFunctionInterface
: public ParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols >
{
public:
typedef ParametricFunctionInterface< DomainFieldImp, domainDim,
RangeFieldImp, rangeDimRows, rangeDimCols > ParametricFunctionType;
static const std::string static_id()
{
return "affineparametricfunction";
}
virtual std::string id() const
{
return static_id();
}
virtual bool hasAffinePart() const = 0;
ParametricFunctionType* affinePart() const = 0;
unsigned int size() const = 0;
ParameterFunctional* coefficient(int ii) const = 0;
ParametricFunctionType* component(int ii) const = 0;
}; // class AffineParametricFunctionInterface
} // namespace Pymor
} // namespace Dune
#endif // DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
<commit_msg>[functions.interfaces] some fixes<commit_after>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
#define DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
#include <dune/common/fmatrix.hh>
#include <dune/common/fvector.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include <dune/pymor/common/exceptions.hh>
namespace Dune {
namespace Pymor {
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class ParametricFunctionInterface
: public Parametric
{
public:
typedef DomainFieldImp DomainFieldType;
static const unsigned int dimDomain = domainDim;
typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRangeRows = rangeDimRows;
static const unsigned int dimRangeCols = rangeDimCols;
typedef Dune::FieldMatrix< RangeFieldType, dimRangeRows, dimRangeCols > RangeType;
template< class... Args >
ParametricFunctionInterface(Args&& ...args)
: Parametric(std::forward< Args >(args)...)
{}
static const std::string static_id()
{
return "parametricfunction";
}
virtual std::string id() const
{
return static_id();
}
virtual int order() const
{
return -1;
}
virtual evaluate(const DomainType& x, RangeType& ret, const Parameter mu = Parameter()) const = 0;
virtual RangeType evaluate(const DomainType& x, const Parameter mu = Parameter()) const
{
if (mu.type() != Parametric::parameter_type())
DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
"type of mu (" << mu.type() << ") does not match the parameter_type of this ("
<< Parametric::parameter_type() << ")!");
RangeType ret;
evaluate(x, ret, mu);
return ret;
}
}; // class ParametricFunctionInterface
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows >
class ParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, 1 >
: public Parametric
{
public:
typedef DomainFieldImp DomainFieldType;
static const unsigned int dimDomain = domainDim;
typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;
typedef RangeFieldImp RangeFieldType;
static const unsigned int dimRangeRows = rangeDimRows;
static const unsigned int dimRangeCols = 1;
static const unsigned int dimRange = 1;
typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;
template< class... Args >
ParametricFunctionInterface(Args&& ...args)
: Parametric(std::forward< Args >(args)...)
{}
static const std::string static_id()
{
return "parametricfunction";
}
virtual std::string id() const
{
return static_id();
}
virtual int order() const
{
return -1;
}
virtual evaluate(const DomainType& x, RangeType& ret, const Parameter mu = Parameter()) const = 0;
virtual RangeType evaluate(const DomainType& x, const Parameter mu = Parameter()) const
{
if (mu.type() != Parametric::parameter_type())
DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
"type of mu (" << mu.type() << ") does not match the parameter_type of this ("
<< Parametric::parameter_type() << ")!");
RangeType ret;
evaluate(x, ret, mu);
return ret;
}
}; // class ParametricFunctionInterface< ..., 1 >
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class AffineParametricFunctionInterface
: public ParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols >
{
public:
typedef ParametricFunctionInterface< DomainFieldImp, domainDim,
RangeFieldImp, rangeDimRows, rangeDimCols > ParametricFunctionType;
static const std::string static_id()
{
return "affineparametricfunction";
}
virtual std::string id() const
{
return static_id();
}
virtual bool hasAffinePart() const = 0;
ParametricFunctionType* affinePart() const = 0;
unsigned int size() const = 0;
ParameterFunctional* coefficient(int ii) const = 0;
ParametricFunctionType* component(int ii) const = 0;
}; // class AffineParametricFunctionInterface
} // namespace Pymor
} // namespace Dune
#endif // DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkBalloonForce3DFilter.h"
#include "itkBalloonForceFilter.h"
#include "itkClassifier.h"
#include "itkConnectedRegionsMeshFilter.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkDeformableMesh.h"
#include "itkExtensionVelocitiesImageFilter.h"
#include "itkFastMarchingExtensionImageFilter.h"
#include "itkFastMarchingImageFilter.h"
#include "itkFuzzyConnectednessImageFilter.h"
#include "itkFuzzyConnectednessRGBImageFilter.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGeodesicActiveContourImageFilter.h"
#include "itkGibbsPriorFilter.h"
#include "itkHybridFilter.h"
#include "itkImageMapper.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkImageToImageMomentsAlignmentCalculator.h"
#include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkKLMRegionGrowImageFilter.h"
#include "itkKLMSegmentationBorder.h"
#include "itkKLMSegmentationRegion.h"
#include "itkKMeansUnsupervisedClassifier.h"
#include "itkKalmanLinearEstimator.h"
#include "itkKernelFunction.h"
#include "itkLevelSet.h"
#include "itkLevelSetImageFilter.h"
#include "itkLevelSetNeighborhoodExtractor.h"
#include "itkLevelSetVelocityNeighborhoodExtractor.h"
#include "itkMRFImageFilter.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMultiResolutionImagePyramid.h"
#include "itkMultiResolutionMutualInformationRigidRegistration.h"
#include "itkMultiResolutionRegistration.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkPatternIntensityPointSetToImageMetric.h"
#include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkProcrustesRegistrationMetric.h"
#include "itkRGBGibbsPriorFilter.h"
#include "itkRegionGrowImageFilter.h"
#include "itkRegistrationMapper.h"
#include "itkRegistrationMapperImage.h"
#include "itkRegistrationMapperProcrustes.h"
#include "itkRegistrationMethod.h"
#include "itkRegistrationTransform.h"
#include "itkReinitializeLevelSetImageFilter.h"
#include "itkRelabelWatershedImageFilter.h"
#include "itkSegmentationBorder.h"
#include "itkSegmentationRegion.h"
#include "itkShapeDetectionLevelSetFilter.h"
#include "itkSimilarityRegistrationMetric.h"
#include "itkSupervisedClassifier.h"
#include "itkUnsupervisedClassifier.h"
#include "itkVectorFuzzyConnectednessImageFilter.h"
#include "itkVoronoi2DDiagram.h"
#include "itkVoronoiSegmentationImageFilter.h"
#include "itkVoronoiSegmentationRGBImageFilter.h"
#include "itkWatershedImageFilter.h"
int main ( int argc, char* argv )
{
return 0;
}
<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkBalloonForce3DFilter.h"
#include "itkBalloonForceFilter.h"
#include "itkClassifier.h"
#include "itkConnectedRegionsMeshFilter.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkDeformableMesh.h"
#include "itkExtensionVelocitiesImageFilter.h"
#include "itkFastMarchingExtensionImageFilter.h"
#include "itkFastMarchingImageFilter.h"
#include "itkFuzzyConnectednessImageFilter.h"
#include "itkFuzzyConnectednessRGBImageFilter.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGeodesicActiveContourImageFilter.h"
#include "itkGibbsPriorFilter.h"
#include "itkHybridFilter.h"
#include "itkImageMapper.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkImageToImageMomentsAlignmentCalculator.h"
#include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkKLMRegionGrowImageFilter.h"
#include "itkKLMSegmentationBorder.h"
#include "itkKLMSegmentationRegion.h"
#include "itkKMeansUnsupervisedClassifier.h"
#include "itkKalmanLinearEstimator.h"
#include "itkKernelFunction.h"
#include "itkLevelSet.h"
#include "itkLevelSetImageFilter.h"
#include "itkLevelSetNeighborhoodExtractor.h"
#include "itkLevelSetVelocityNeighborhoodExtractor.h"
#include "itkMRFImageFilter.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMultiResolutionImagePyramid.h"
#include "itkMultiResolutionMutualInformationAffineRegistration.h"
#include "itkMultiResolutionMutualInformationRigidRegistration.h"
#include "itkMultiResolutionRegistration.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkPatternIntensityPointSetToImageMetric.h"
#include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkProcrustesRegistrationMetric.h"
#include "itkRGBGibbsPriorFilter.h"
#include "itkRegionGrowImageFilter.h"
#include "itkRegistrationMapper.h"
#include "itkRegistrationMapperImage.h"
#include "itkRegistrationMapperProcrustes.h"
#include "itkRegistrationMethod.h"
#include "itkRegistrationTransform.h"
#include "itkReinitializeLevelSetImageFilter.h"
#include "itkRelabelWatershedImageFilter.h"
#include "itkSegmentationBorder.h"
#include "itkSegmentationRegion.h"
#include "itkShapeDetectionLevelSetFilter.h"
#include "itkSimilarityRegistrationMetric.h"
#include "itkSupervisedClassifier.h"
#include "itkUnsupervisedClassifier.h"
#include "itkVectorFuzzyConnectednessImageFilter.h"
#include "itkVoronoi2DDiagram.h"
#include "itkVoronoiSegmentationImageFilter.h"
#include "itkVoronoiSegmentationRGBImageFilter.h"
#include "itkWatershedImageFilter.h"
int main ( int argc, char* argv )
{
return 0;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module: itkNeighborhoodOperatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkScalar.h"
#include "itkRandomImageSource.h"
#include "itkFilterImageSingleOperator.h"
#include "itkWriteVTKImage.h"
int main()
{
// Create a source
itk::RandomImageSource< itk::Image<itk::Scalar<float>,2> >::Pointer random;
random = itk::RandomImageSource< itk::Image<itk::Scalar<float>,2> >::New();
// Create a neighborhood
itk::NeighborhoodOperator< itkScalar<float>, 3> *neighborhood
= itk::NeighborhoodOperator< itkScalar<float, 3>::New();
// Create a filter
itk::FilterImageSingleOperator< itkScalar<float>, 3>::Pointer filter;
filter = itk::FilterImageSingleOperator< itkScalar<float>, 3>::New();
filter->SetInput( random->GetOutput() );
filter->SetOperator( neighborhood );
// Create a mapper
itk::WriteVTKImage< itk::Image<itk::Scalar<float>,2> >::Pointer writer;
writer = itk::WriteVTKImage< itk::Image<itk::Scalar<float>,2> >::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName("junkImage.vtk");
writer->SetFileTypeToASCII();
writer->DebugOn();
writer->Write();
return 1;
}
<commit_msg>BUG: Fixed some typos.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module: itkNeighborhoodOperatorTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkScalar.h"
#include "itkRandomImageSource.h"
#include "itkFilterImageSingleOperator.h"
#include "itkWriteVTKImage.h"
int main()
{
// Create a source
itk::RandomImageSource< itk::Image<itk::Scalar<float>,2> >::Pointer random;
random = itk::RandomImageSource< itk::Image<itk::Scalar<float>,2> >::New();
// Create a neighborhood
itk::Neighborhood< itk::Scalar<float>, 2> neighborhood;
neighborhood.SetRadius(1);
// Create a filter
itk::FilterImageSingleOperator< itk::Scalar<float>, 2>::Pointer filter;
filter = itk::FilterImageSingleOperator< itk::Scalar<float>, 2>::New();
filter->SetInput( random->GetOutput() );
filter->SetOperator( neighborhood );
// Create a mapper
itk::WriteVTKImage< itk::Image<itk::Scalar<float>,2> >::Pointer writer;
writer = itk::WriteVTKImage< itk::Image<itk::Scalar<float>,2> >::New();
writer->SetInput(filter->GetOutput());
writer->SetFileName("junkImage.vtk");
writer->SetFileTypeToASCII();
writer->DebugOn();
writer->Write();
return 1;
}
<|endoftext|>
|
<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// 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 ofMERCHANTABILITY
// 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
// ===========================================================================
//
// Authors:
// Eugen Wintersberger <eugen.wintersberger@desy.de>
// Martin Shetty <martin.shetty@esss.se>
// Created on: Aug 23, 2017
//
#include <gtest/gtest.h>
#include <h5cpp/datatype/factory.hpp>
#include <h5cpp/datatype/integer.hpp>
using namespace hdf5;
template<class T>
class Integer : public testing::Test {
protected:
Integer() {}
virtual ~Integer() {}
T value_;
};
template <class T>
class SignedInteger : public Integer<T> { };
template <class T>
class UnsignedInteger : public Integer<T> { };
using testing::Types;
// The list of types we want to test.
typedef
Types<
char, unsigned char, signed char,
short, unsigned short,
int, unsigned int,
long, unsigned long,
long long, unsigned long long>
test_types;
// The list of unsigned types we want to test.
typedef
Types<
unsigned char,
unsigned short,
unsigned int,
unsigned long,
unsigned long long>
test_unsigned_types;
// The list of signed types we want to test.
typedef
Types<char, signed char, short, int, long, long long>
test_signed_types;
TYPED_TEST_CASE(Integer, test_types);
TYPED_TEST_CASE(SignedInteger, test_signed_types);
TYPED_TEST_CASE(UnsignedInteger, test_unsigned_types);
TYPED_TEST(Integer, Exceptions) {
datatype::Datatype dtype;
EXPECT_THROW((datatype::Integer(dtype)), std::runtime_error);
auto ft = datatype::create<double>();
EXPECT_THROW((datatype::Integer(ft)), std::runtime_error);
}
TYPED_TEST(Integer, General) {
auto t = datatype::create<decltype(this->value_)>();
EXPECT_TRUE((std::is_same<decltype(t), datatype::Integer>::value));
EXPECT_TRUE(t.get_class() == datatype::Class::INTEGER);
EXPECT_EQ(t.size(), sizeof(this->value_));
datatype::Datatype &generic = t;
datatype::Integer new_type(generic);
EXPECT_EQ(new_type.get_class(), datatype::Class::INTEGER);
datatype::Datatype default_constructed;
EXPECT_FALSE(default_constructed.is_valid());
EXPECT_THROW((datatype::Integer(default_constructed)), std::runtime_error);
}
TYPED_TEST(SignedInteger, Signed) {
auto t = datatype::create<decltype(this->value_)>();
ASSERT_EQ(t.is_signed(), true);
t.make_signed(true);
ASSERT_EQ(t.is_signed(), true);
t.make_signed(false);
ASSERT_EQ(t.is_signed(), false);
}
TYPED_TEST(UnsignedInteger, Signed) {
auto t = datatype::create<decltype(this->value_)>();
ASSERT_EQ(t.is_signed(), false);
t.make_signed(true);
ASSERT_EQ(t.is_signed(), true);
t.make_signed(false);
ASSERT_EQ(t.is_signed(), false);
}
<commit_msg>relax char tests for signed<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// 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 ofMERCHANTABILITY
// 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
// ===========================================================================
//
// Authors:
// Eugen Wintersberger <eugen.wintersberger@desy.de>
// Martin Shetty <martin.shetty@esss.se>
// Created on: Aug 23, 2017
//
#include <gtest/gtest.h>
#include <h5cpp/datatype/factory.hpp>
#include <h5cpp/datatype/integer.hpp>
using namespace hdf5;
template<class T>
class Integer : public testing::Test {
protected:
Integer() {}
virtual ~Integer() {}
T value_;
};
template <class T>
class SignedInteger : public Integer<T> { };
template <class T>
class UnsignedInteger : public Integer<T> { };
using testing::Types;
// The list of types we want to test.
typedef
Types<
char, unsigned char, signed char,
short, unsigned short,
int, unsigned int,
long, unsigned long,
long long, unsigned long long>
test_types;
// The list of unsigned types we want to test.
typedef
Types<
unsigned char,
unsigned short,
unsigned int,
unsigned long,
unsigned long long>
test_unsigned_types;
// The list of signed types we want to test.
typedef
Types<signed char, short, int, long, long long>
test_signed_types;
TYPED_TEST_CASE(Integer, test_types);
TYPED_TEST_CASE(SignedInteger, test_signed_types);
TYPED_TEST_CASE(UnsignedInteger, test_unsigned_types);
TYPED_TEST(Integer, Exceptions) {
datatype::Datatype dtype;
EXPECT_THROW((datatype::Integer(dtype)), std::runtime_error);
auto ft = datatype::create<double>();
EXPECT_THROW((datatype::Integer(ft)), std::runtime_error);
}
TYPED_TEST(Integer, General) {
auto t = datatype::create<decltype(this->value_)>();
EXPECT_TRUE((std::is_same<decltype(t), datatype::Integer>::value));
EXPECT_TRUE(t.get_class() == datatype::Class::INTEGER);
EXPECT_EQ(t.size(), sizeof(this->value_));
datatype::Datatype &generic = t;
datatype::Integer new_type(generic);
EXPECT_EQ(new_type.get_class(), datatype::Class::INTEGER);
datatype::Datatype default_constructed;
EXPECT_FALSE(default_constructed.is_valid());
EXPECT_THROW((datatype::Integer(default_constructed)), std::runtime_error);
}
TYPED_TEST(SignedInteger, Signed) {
auto t = datatype::create<decltype(this->value_)>();
ASSERT_EQ(t.is_signed(), true);
t.make_signed(true);
ASSERT_EQ(t.is_signed(), true);
t.make_signed(false);
ASSERT_EQ(t.is_signed(), false);
}
TYPED_TEST(UnsignedInteger, Signed) {
auto t = datatype::create<decltype(this->value_)>();
ASSERT_EQ(t.is_signed(), false);
t.make_signed(true);
ASSERT_EQ(t.is_signed(), true);
t.make_signed(false);
ASSERT_EQ(t.is_signed(), false);
}
<|endoftext|>
|
<commit_before>#ifndef PK_DEPTHFIRSTSEARCH_HPP
#define PK_DEPTHFIRSTSEARCH_HPP
#include <algorithm>
#include "stack.hpp"
namespace pk
{
class depth_first_search
{
public:
template<
class graph_type,
class visitor_type>
static void run(
const graph_type& g,
const int starting_vertex_id,
visitor_type& visitor)
{
pk::stack<int, graph_type::max_num_of_edges> s;
bool visited[graph_type::num_of_vertices];
std::fill(visited, visited + graph_type::num_of_vertices, false);
s.push(starting_vertex_id);
while(!s.empty())
{
const int v = s.top();
s.pop();
if(visited[v])
continue;
visitor.visit(v);
visited[v] = true;
const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v);
for(int i = adj_v.size(); i >= 0; --i)
{
const int u = adj_v[i].to;
if(visited[u])
continue;
s.push(u);
}
}
}
};
} // namespace pk
#endif // PK_DEPTHFIRSTSEARCH_HPP
<commit_msg>Fixed DFS algorithm<commit_after>#ifndef PK_DEPTHFIRSTSEARCH_HPP
#define PK_DEPTHFIRSTSEARCH_HPP
#include <algorithm>
#include "stack.hpp"
namespace pk
{
class depth_first_search
{
public:
template<
class graph_type,
class visitor_type>
static void run(
const graph_type& g,
const int starting_vertex_id,
visitor_type& visitor)
{
pk::stack<int, graph_type::max_num_of_edges> s;
bool visited[graph_type::num_of_vertices];
std::fill(visited, visited + graph_type::num_of_vertices, false);
s.push(starting_vertex_id);
while(!s.empty())
{
const int v = s.top();
s.pop();
if(visited[v])
continue;
visitor.visit(v);
visited[v] = true;
const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v);
for(int i = adj_v.size() - 1; i >= 0; --i)
{
const int u = adj_v[i].to;
if(visited[u])
continue;
s.push(u);
}
}
}
};
} // namespace pk
#endif // PK_DEPTHFIRSTSEARCH_HPP
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "settingslayer_symbian.h"
#include <QVariant>
#include "xqsettingskey.h"
#include "xqpublishandsubscribeutils.h"
#include <QDebug>
Q_GLOBAL_STATIC(SymbianSettingsLayer, symbianSettingsLayer);
QVALUESPACE_AUTO_INSTALL_LAYER(SymbianSettingsLayer);
QT_BEGIN_NAMESPACE
SymbianSettingsLayer::SymbianSettingsLayer()
{
qDebug("SymbianSettingsLayer::SymbianSettingsLayer()");
connect(&m_settingsManager, SIGNAL(valueChanged(const XQSettingsKey&, const QVariant&)),
this, SLOT(valueChanged(const XQSettingsKey&, const QVariant&)));
}
SymbianSettingsLayer::~SymbianSettingsLayer()
{
qDebug("SymbianSettingsLayer::~SymbianSettingsLayer()");
QMutableHashIterator<QString, SymbianSettingsHandle *> i(handles);
while (i.hasNext()) {
i.next();
SymbianSettingsHandle *handle = i.value();
if (handle->valueHandle)
removeHandle(Handle(handle));
}
i.toFront();
while (i.hasNext()) {
i.next();
removeHandle(Handle(i.value()));
}
}
QString SymbianSettingsLayer::name()
{
return QLatin1String("Symbian Settings Layer");
}
QUuid SymbianSettingsLayer::id()
{
return QVALUESPACE_SYMBIAN_SETTINGS_LAYER;
}
unsigned int SymbianSettingsLayer::order()
{
return 0;
}
QValueSpace::LayerOptions SymbianSettingsLayer::layerOptions() const
{
return QValueSpace::PermanentLayer |
QValueSpace::WriteableLayer;
}
SymbianSettingsLayer *SymbianSettingsLayer::instance()
{
return symbianSettingsLayer();
}
bool SymbianSettingsLayer::startup(Type type)
{
qDebug("bool SymbianSettingsLayer::startup(Type type)");
return true;
}
bool SymbianSettingsLayer::value(Handle handle, QVariant *data)
{
qDebug("bool SymbianSettingsLayer::value(Handle handle, QVariant *data)");
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return false;
return value(InvalidHandle, sh->path, data);
}
bool SymbianSettingsLayer::value(Handle handle, const QString &subPath, QVariant *data)
{
qDebug("bool SymbianSettingsLayer::value(Handle handle, const QString &subPath, QVariant *data)");
if (handle != InvalidHandle && !symbianSettingsHandle(handle))
return false;
QString path(subPath);
while (path.endsWith(QLatin1Char('/')))
path.chop(1);
if (handle != InvalidHandle)
while (path.startsWith(QLatin1Char('/')))
path = path.mid(1);
int index = path.lastIndexOf(QLatin1Char('/'), -1);
bool createdHandle = false;
QString value;
if (index == -1) {
value = path;
} else {
// want a value that is in a sub path under handle
value = path.mid(index + 1);
path.truncate(index);
handle = item(handle, path);
createdHandle = true;
}
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
QString fullPath(sh->path);
if (fullPath != QLatin1String("/"))
fullPath.append(QLatin1Char('/'));
fullPath.append(value);
bool success = false;
if (sh) {
PathMapper::Target target;
quint32 category;
quint32 key;
if (pathMapper.resolvePath(fullPath, target, category, key)) {
XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
*data = m_settingsManager.readItemValue(settingsKey);
if (!data->isNull()) {
success = true;
}
}
}
if (createdHandle)
removeHandle(handle);
return success;
}
QSet<QString> SymbianSettingsLayer::children(Handle handle)
{
qDebug("QSet<QString> SymbianSettingsLayer::children(Handle handle)");
QSet<QString> foundChildren;
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return foundChildren;
pathMapper.getChildren(sh->path, foundChildren);
return foundChildren;
}
QAbstractValueSpaceLayer::Handle SymbianSettingsLayer::item(Handle parent, const QString &path)
{
qDebug("QAbstractValueSpaceLayer::Handle SymbianSettingsLayer::item(Handle parent, const QString &path)");
QString fullPath;
// Fail on invalid path.
if (path.isEmpty() || path.contains(QLatin1String("//")))
return InvalidHandle;
if (parent == InvalidHandle) {
fullPath = path;
} else {
SymbianSettingsHandle *sh = symbianSettingsHandle(parent);
if (!sh)
return InvalidHandle;
if (path == QLatin1String("/")) {
fullPath = sh->path;
} else if (sh->path.endsWith(QLatin1Char('/')) && path.startsWith(QLatin1Char('/')))
fullPath = sh->path + path.mid(1);
else if (!sh->path.endsWith(QLatin1Char('/')) && !path.startsWith(QLatin1Char('/')))
fullPath = sh->path + QLatin1Char('/') + path;
else
fullPath = sh->path + path;
}
if (handles.contains(fullPath)) {
SymbianSettingsHandle *sh = handles.value(fullPath);
++sh->refCount;
return Handle(sh);
}
// Create a new handle for path
SymbianSettingsHandle *sh = new SymbianSettingsHandle(fullPath);
handles.insert(fullPath, sh);
return Handle(sh);
}
void SymbianSettingsLayer::setProperty(Handle handle, Properties properties)
{
qDebug("void SymbianSettingsLayer::setProperty(Handle handle, Properties properties)");
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return;
if (properties & QAbstractValueSpaceLayer::Publish) {
QSet<QString> children;
pathMapper.getChildren(sh->path, children);
foreach(QString child, children) {
QString fullPath = sh->path;
if (fullPath.right(1) != QLatin1String("/"))
fullPath += QLatin1Char('/');
fullPath += child;
PathMapper::Target target;
quint32 category;
quint32 key;
if (pathMapper.resolvePath(fullPath, target, category, key)) {
XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
m_settingsManager.startMonitoring(settingsKey);
}
QByteArray hash;
hash += qHash(target);
hash += qHash((long)category);
hash += qHash((unsigned long)key);
m_monitoringHandles[hash] = sh;
}
}
if (!(properties & QAbstractValueSpaceLayer::Publish)) {
QSet<QString> children;
pathMapper.getChildren(sh->path, children);
foreach(QString child, children) {
QString fullPath = sh->path;
if (fullPath.right(1) != QLatin1String("/"))
fullPath += QLatin1Char('/');
fullPath += child;
qDebug() << "TODO: Actual code for stop monitoring" << fullPath;
}
}
}
void SymbianSettingsLayer::removeHandle(Handle handle)
{
qDebug("void SymbianSettingsLayer::removeHandle(Handle handle)");
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return;
if (--sh->refCount)
return;
handles.remove(sh->path);
delete sh;
}
bool SymbianSettingsLayer::setValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath,
const QVariant &data)
{
qDebug("bool SymbianSettingsLayer::setValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath, const QVariant &data)");
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return false;
QString path(subPath);
while (path.endsWith(QLatin1Char('/')))
path.chop(1);
int index = path.lastIndexOf(QLatin1Char('/'), -1);
bool createdHandle = false;
QString value;
if (index == -1) {
value = path;
} else {
// want a value that is in a sub path under handle
value = path.mid(index + 1);
path.truncate(index);
if (path.isEmpty())
path.append(QLatin1Char('/'));
sh = symbianSettingsHandle(item(Handle(sh), path));
createdHandle = true;
}
QString fullPath(sh->path);
if (fullPath != QLatin1String("/"))
fullPath.append(QLatin1Char('/'));
fullPath.append(value);
bool success = false;
PathMapper::Target target;
quint32 category;
quint32 key;
if (pathMapper.resolvePath(fullPath, target, category, key)) {
if (target == PathMapper::TargetRPropery) {
XQPublishAndSubscribeUtils utils(m_settingsManager);
XQSettingsManager::Type type = XQSettingsManager::TypeVariant;
switch (data.type()) {
case QVariant::Int: type = XQSettingsManager::TypeInt; break;
case QVariant::String: type = XQSettingsManager::TypeString; break;
case QVariant::ByteArray: type = XQSettingsManager::TypeByteArray; break;
default:
return false;
}
utils.defineProperty(XQPublishAndSubscribeSettingsKey((long)category, (unsigned long)key), type);
}
XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
success = m_settingsManager.writeItemValue(settingsKey, data);
}
if (createdHandle)
removeHandle(Handle(sh));
return success;
}
void SymbianSettingsLayer::sync()
{
qDebug("void SymbianSettingsLayer::sync()");
//TODO: Is this needed in Symbian?
}
bool SymbianSettingsLayer::removeSubTree(QValueSpaceProvider *creator, Handle handle)
{
qDebug("bool SymbianSettingsLayer::removeSubTree(QValueSpaceProvider *creator, Handle handle)");
//TODO: Is this needed in Symbian?
return false;
}
bool SymbianSettingsLayer::removeValue(QValueSpaceProvider *creator,
Handle handle,
const QString &subPath)
{
qDebug("bool SymbianSettingsLayer::removeValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath)");
//TODO: Is this needed in Symbian?
return false;
}
void SymbianSettingsLayer::addWatch(QValueSpaceProvider *, Handle)
{
qDebug("void SymbianSettingsLayer::addWatch(QValueSpaceProvider *, Handle)");
}
void SymbianSettingsLayer::removeWatches(QValueSpaceProvider *, Handle)
{
qDebug("void SymbianSettingsLayer::removeWatches(QValueSpaceProvider *, Handle)");
}
bool SymbianSettingsLayer::supportsInterestNotification() const
{
qDebug("bool SymbianSettingsLayer::supportsInterestNotification() const");
return false;
}
bool SymbianSettingsLayer::notifyInterest(Handle, bool)
{
qDebug("bool SymbianSettingsLayer::notifyInterest(Handle, bool)");
return false;
}
void SymbianSettingsLayer::valueChanged(const XQSettingsKey& key, const QVariant& value)
{
qDebug("void SymbianSettingsLayer::valueChanged(const XQSettingsKey& key, const QVariant& value)");
QByteArray hash;
hash += qHash(key.target());
hash += qHash(key.uid());
hash += qHash(key.key());
if (m_monitoringHandles.contains(hash)) {
emit handleChanged(Handle(m_monitoringHandles.value(hash)));
}
}
QT_END_NAMESPACE
<commit_msg>Stop monitoring<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "settingslayer_symbian.h"
#include <QVariant>
#include "xqsettingskey.h"
#include "xqpublishandsubscribeutils.h"
#include <QDebug>
Q_GLOBAL_STATIC(SymbianSettingsLayer, symbianSettingsLayer);
QVALUESPACE_AUTO_INSTALL_LAYER(SymbianSettingsLayer);
QT_BEGIN_NAMESPACE
SymbianSettingsLayer::SymbianSettingsLayer()
{
qDebug("SymbianSettingsLayer::SymbianSettingsLayer()");
connect(&m_settingsManager, SIGNAL(valueChanged(const XQSettingsKey&, const QVariant&)),
this, SLOT(valueChanged(const XQSettingsKey&, const QVariant&)));
}
SymbianSettingsLayer::~SymbianSettingsLayer()
{
qDebug("SymbianSettingsLayer::~SymbianSettingsLayer()");
QMutableHashIterator<QString, SymbianSettingsHandle *> i(handles);
while (i.hasNext()) {
i.next();
SymbianSettingsHandle *handle = i.value();
if (handle->valueHandle)
removeHandle(Handle(handle));
}
i.toFront();
while (i.hasNext()) {
i.next();
removeHandle(Handle(i.value()));
}
}
QString SymbianSettingsLayer::name()
{
return QLatin1String("Symbian Settings Layer");
}
QUuid SymbianSettingsLayer::id()
{
return QVALUESPACE_SYMBIAN_SETTINGS_LAYER;
}
unsigned int SymbianSettingsLayer::order()
{
return 0;
}
QValueSpace::LayerOptions SymbianSettingsLayer::layerOptions() const
{
return QValueSpace::PermanentLayer |
QValueSpace::WriteableLayer;
}
SymbianSettingsLayer *SymbianSettingsLayer::instance()
{
return symbianSettingsLayer();
}
bool SymbianSettingsLayer::startup(Type type)
{
qDebug("bool SymbianSettingsLayer::startup(Type type)");
return true;
}
bool SymbianSettingsLayer::value(Handle handle, QVariant *data)
{
qDebug("bool SymbianSettingsLayer::value(Handle handle, QVariant *data)");
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return false;
return value(InvalidHandle, sh->path, data);
}
bool SymbianSettingsLayer::value(Handle handle, const QString &subPath, QVariant *data)
{
qDebug("bool SymbianSettingsLayer::value(Handle handle, const QString &subPath, QVariant *data)");
if (handle != InvalidHandle && !symbianSettingsHandle(handle))
return false;
QString path(subPath);
while (path.endsWith(QLatin1Char('/')))
path.chop(1);
if (handle != InvalidHandle)
while (path.startsWith(QLatin1Char('/')))
path = path.mid(1);
int index = path.lastIndexOf(QLatin1Char('/'), -1);
bool createdHandle = false;
QString value;
if (index == -1) {
value = path;
} else {
// want a value that is in a sub path under handle
value = path.mid(index + 1);
path.truncate(index);
handle = item(handle, path);
createdHandle = true;
}
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
QString fullPath(sh->path);
if (fullPath != QLatin1String("/"))
fullPath.append(QLatin1Char('/'));
fullPath.append(value);
bool success = false;
if (sh) {
PathMapper::Target target;
quint32 category;
quint32 key;
if (pathMapper.resolvePath(fullPath, target, category, key)) {
XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
*data = m_settingsManager.readItemValue(settingsKey);
if (!data->isNull()) {
success = true;
}
}
}
if (createdHandle)
removeHandle(handle);
return success;
}
QSet<QString> SymbianSettingsLayer::children(Handle handle)
{
qDebug("QSet<QString> SymbianSettingsLayer::children(Handle handle)");
QSet<QString> foundChildren;
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return foundChildren;
pathMapper.getChildren(sh->path, foundChildren);
return foundChildren;
}
QAbstractValueSpaceLayer::Handle SymbianSettingsLayer::item(Handle parent, const QString &path)
{
qDebug("QAbstractValueSpaceLayer::Handle SymbianSettingsLayer::item(Handle parent, const QString &path)");
QString fullPath;
// Fail on invalid path.
if (path.isEmpty() || path.contains(QLatin1String("//")))
return InvalidHandle;
if (parent == InvalidHandle) {
fullPath = path;
} else {
SymbianSettingsHandle *sh = symbianSettingsHandle(parent);
if (!sh)
return InvalidHandle;
if (path == QLatin1String("/")) {
fullPath = sh->path;
} else if (sh->path.endsWith(QLatin1Char('/')) && path.startsWith(QLatin1Char('/')))
fullPath = sh->path + path.mid(1);
else if (!sh->path.endsWith(QLatin1Char('/')) && !path.startsWith(QLatin1Char('/')))
fullPath = sh->path + QLatin1Char('/') + path;
else
fullPath = sh->path + path;
}
if (handles.contains(fullPath)) {
SymbianSettingsHandle *sh = handles.value(fullPath);
++sh->refCount;
return Handle(sh);
}
// Create a new handle for path
SymbianSettingsHandle *sh = new SymbianSettingsHandle(fullPath);
handles.insert(fullPath, sh);
return Handle(sh);
}
void SymbianSettingsLayer::setProperty(Handle handle, Properties properties)
{
qDebug("void SymbianSettingsLayer::setProperty(Handle handle, Properties properties)");
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return;
QSet<QString> children;
pathMapper.getChildren(sh->path, children);
foreach(QString child, children) {
QString fullPath = sh->path;
if (fullPath.right(1) != QLatin1String("/"))
fullPath += QLatin1Char('/');
fullPath += child;
PathMapper::Target target;
quint32 category;
quint32 key;
if (pathMapper.resolvePath(fullPath, target, category, key)) {
XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
QByteArray hash;
hash += qHash(target);
hash += qHash((long)category);
hash += qHash((unsigned long)key);
if (properties & QAbstractValueSpaceLayer::Publish) {
qDebug() << "Start monitoring" << fullPath;
m_settingsManager.startMonitoring(settingsKey);
m_monitoringHandles[hash] = sh;
} else {
qDebug() << "Stop monitoring" << fullPath;
m_settingsManager.stopMonitoring(settingsKey);
m_monitoringHandles.remove(hash);
}
}
}
}
void SymbianSettingsLayer::removeHandle(Handle handle)
{
qDebug("void SymbianSettingsLayer::removeHandle(Handle handle)");
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return;
if (--sh->refCount)
return;
handles.remove(sh->path);
delete sh;
}
bool SymbianSettingsLayer::setValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath,
const QVariant &data)
{
qDebug("bool SymbianSettingsLayer::setValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath, const QVariant &data)");
SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
if (!sh)
return false;
QString path(subPath);
while (path.endsWith(QLatin1Char('/')))
path.chop(1);
int index = path.lastIndexOf(QLatin1Char('/'), -1);
bool createdHandle = false;
QString value;
if (index == -1) {
value = path;
} else {
// want a value that is in a sub path under handle
value = path.mid(index + 1);
path.truncate(index);
if (path.isEmpty())
path.append(QLatin1Char('/'));
sh = symbianSettingsHandle(item(Handle(sh), path));
createdHandle = true;
}
QString fullPath(sh->path);
if (fullPath != QLatin1String("/"))
fullPath.append(QLatin1Char('/'));
fullPath.append(value);
bool success = false;
PathMapper::Target target;
quint32 category;
quint32 key;
if (pathMapper.resolvePath(fullPath, target, category, key)) {
if (target == PathMapper::TargetRPropery) {
XQPublishAndSubscribeUtils utils(m_settingsManager);
XQSettingsManager::Type type = XQSettingsManager::TypeVariant;
switch (data.type()) {
case QVariant::Int: type = XQSettingsManager::TypeInt; break;
case QVariant::String: type = XQSettingsManager::TypeString; break;
case QVariant::ByteArray: type = XQSettingsManager::TypeByteArray; break;
default:
return false;
}
utils.defineProperty(XQPublishAndSubscribeSettingsKey((long)category, (unsigned long)key), type);
}
XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
success = m_settingsManager.writeItemValue(settingsKey, data);
}
if (createdHandle)
removeHandle(Handle(sh));
return success;
}
void SymbianSettingsLayer::sync()
{
qDebug("void SymbianSettingsLayer::sync()");
//TODO: Is this needed in Symbian?
}
bool SymbianSettingsLayer::removeSubTree(QValueSpaceProvider *creator, Handle handle)
{
qDebug("bool SymbianSettingsLayer::removeSubTree(QValueSpaceProvider *creator, Handle handle)");
//TODO: Is this needed in Symbian?
return false;
}
bool SymbianSettingsLayer::removeValue(QValueSpaceProvider *creator,
Handle handle,
const QString &subPath)
{
qDebug("bool SymbianSettingsLayer::removeValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath)");
//TODO: Is this needed in Symbian?
return false;
}
void SymbianSettingsLayer::addWatch(QValueSpaceProvider *, Handle)
{
qDebug("void SymbianSettingsLayer::addWatch(QValueSpaceProvider *, Handle)");
}
void SymbianSettingsLayer::removeWatches(QValueSpaceProvider *, Handle)
{
qDebug("void SymbianSettingsLayer::removeWatches(QValueSpaceProvider *, Handle)");
}
bool SymbianSettingsLayer::supportsInterestNotification() const
{
qDebug("bool SymbianSettingsLayer::supportsInterestNotification() const");
return false;
}
bool SymbianSettingsLayer::notifyInterest(Handle, bool)
{
qDebug("bool SymbianSettingsLayer::notifyInterest(Handle, bool)");
return false;
}
void SymbianSettingsLayer::valueChanged(const XQSettingsKey& key, const QVariant& value)
{
qDebug("void SymbianSettingsLayer::valueChanged(const XQSettingsKey& key, const QVariant& value)");
QByteArray hash;
hash += qHash(key.target());
hash += qHash(key.uid());
hash += qHash(key.key());
if (m_monitoringHandles.contains(hash)) {
emit handleChanged(Handle(m_monitoringHandles.value(hash)));
}
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>#pragma once
#include <stdexcept>
namespace lw {
namespace error {
class Exception : public std::runtime_error {
public:
Exception( const std::int64_t code, const std::string& message ):
std::runtime_error( message ),
m_error_code( code )
{}
// ---------------------------------------------------------------------- //
std::int64_t error_code( void ) const {
return m_error_code;
}
// ---------------------------------------------------------------------- //
private:
std::int64_t m_error_code;
};
// -------------------------------------------------------------------------- //
#define LW_DEFINE_EXCEPTION_EX( _Type, _ParentNamespace, _Parent ) \
class _Type : public _ParentNamespace::_Parent { \
public: \
using _ParentNamespace::_Parent::_Parent; \
};
#define LW_DEFINE_EXCEPTION( _Type ) \
LW_DEFINE_EXCEPTION_EX( _Type, ::lw::error, Exception )
}
}
<commit_msg>Added UV-error macro<commit_after>#pragma once
#include <stdexcept>
namespace lw {
namespace error {
class Exception : public std::runtime_error {
public:
Exception( const std::int64_t code, const std::string& message ):
std::runtime_error( message ),
m_error_code( code )
{}
// ---------------------------------------------------------------------- //
std::int64_t error_code( void ) const {
return m_error_code;
}
// ---------------------------------------------------------------------- //
private:
std::int64_t m_error_code;
};
// -------------------------------------------------------------------------- //
#define LW_DEFINE_EXCEPTION_EX( _Type, _ParentNamespace, _Parent ) \
class _Type : public _ParentNamespace::_Parent { \
public: \
using _ParentNamespace::_Parent::_Parent; \
};
#define LW_DEFINE_EXCEPTION( _Type ) \
LW_DEFINE_EXCEPTION_EX( _Type, ::lw::error, Exception )
// -------------------------------------------------------------------------- //
#define LW_UV_ERROR( _Type, _code ) \
_Type( _code, (std::string)uv_err_name( _code ) + ": " + uv_strerror( _code ) )
}
}
<|endoftext|>
|
<commit_before>/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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 <gtest/gtest.h>
#include <ubiquity_motor/motor_serial.h>
#include <ubiquity_motor/motor_message.h>
#include <ros/ros.h>
#include <string>
#if defined(__linux__)
#include <pty.h>
#else
#include <util.h>
#endif
class MotorSerialTests : public ::testing::Test {
protected:
virtual void SetUp() {
if (openpty(&master_fd, &slave_fd, name, NULL, NULL) == -1) {
perror("openpty");
exit(127);
}
ASSERT_TRUE(master_fd > 0);
ASSERT_TRUE(slave_fd > 0);
ASSERT_TRUE(std::string(name).length() > 0);
ros::Time::init();
motors = new MotorSerial(std::string(name), 9600, 1000);
}
virtual void TearDown() {
delete motors;
}
MotorSerial * motors;
int master_fd;
int slave_fd;
char name[100];
};
TEST_F(MotorSerialTests, goodreadWorks){
uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
//char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
write(master_fd, test, 9);
while(!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors-> receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, badreadFails){
uint8_t test[]= {0xdd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
write(master_fd, test, 9);
ros::Rate loop(10);
int times = 0;
while(!motors->commandAvailable()) {
loop.sleep();
times++;
if(times >= 20) {
break;
}
}
if(times >= 20) {
SUCCEED();
}
else {
FAIL();
}
}
TEST_F(MotorSerialTests, writeWorks) {
MotorMessage version;
version.setRegister(MotorMessage::REG_FIRMWARE_VERSION);
version.setType(MotorMessage::TYPE_READ);
version.setData(0);
motors->transmitCommand(version);
uint8_t arr[9];
read(master_fd, arr, 9);
std::vector<uint8_t> input(arr, arr + sizeof(arr)/ sizeof(uint8_t));
ASSERT_EQ(input, version.serialize());
}
TEST_F(MotorSerialTests, writeMultipleWorks) {
std::vector<MotorMessage> commands;
MotorMessage left_odom;
left_odom.setRegister(MotorMessage::REG_LEFT_ODOM);
left_odom.setType(MotorMessage::TYPE_READ);
left_odom.setData(0);
commands.push_back(left_odom);
MotorMessage right_odom;
right_odom.setRegister(MotorMessage::REG_RIGHT_ODOM);
right_odom.setType(MotorMessage::TYPE_READ);
right_odom.setData(0);
commands.push_back(right_odom);
MotorMessage left_vel;
left_vel.setRegister(MotorMessage::REG_LEFT_SPEED_MEASURED);
left_vel.setType(MotorMessage::TYPE_READ);
left_vel.setData(0);
commands.push_back(left_vel);
MotorMessage right_vel;
right_vel.setRegister(MotorMessage::REG_RIGHT_SPEED_MEASURED);
right_vel.setType(MotorMessage::TYPE_READ);
right_vel.setData(0);
commands.push_back(right_vel);
motors->transmitCommands(commands);
uint8_t arr[36];
read(master_fd, arr, 36);
std::vector<uint8_t> input(arr, arr + sizeof(arr)/ sizeof(uint8_t));
std::vector<uint8_t> expected(0);
for (std::vector<MotorMessage>::iterator i = commands.begin(); i != commands.end(); ++i){
std::vector<uint8_t> serialized = i->serialize();
expected.insert(expected.end(), serialized.begin(), serialized.end());
}
ASSERT_EQ(expected, input);
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>Added misaligned test cases<commit_after>/**
Copyright (c) 2016, Ubiquity Robotics
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 ubiquity_motor 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 <gtest/gtest.h>
#include <ubiquity_motor/motor_serial.h>
#include <ubiquity_motor/motor_message.h>
#include <ros/ros.h>
#include <string>
#if defined(__linux__)
#include <pty.h>
#else
#include <util.h>
#endif
class MotorSerialTests : public ::testing::Test {
protected:
virtual void SetUp() {
if (openpty(&master_fd, &slave_fd, name, NULL, NULL) == -1) {
perror("openpty");
exit(127);
}
ASSERT_TRUE(master_fd > 0);
ASSERT_TRUE(slave_fd > 0);
ASSERT_TRUE(std::string(name).length() > 0);
ros::Time::init();
motors = new MotorSerial(std::string(name), 9600, 1000);
}
virtual void TearDown() {
delete motors;
}
MotorSerial * motors;
int master_fd;
int slave_fd;
char name[100];
};
TEST_F(MotorSerialTests, goodReadWorks){
uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
//char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
write(master_fd, test, 9);
while(!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors-> receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, misalignedOneGoodReadWorks){
uint8_t test[]= {0x00, 0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
//char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
write(master_fd, test, 10);
while(!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors-> receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, misalignedManyGoodReadWorks){
uint8_t test[]= {0x01, 0x2C, 0x0E, 0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
//char test[]= {0x0E, 0x2C, 0x01, 0x00, 0x00, 0x07, 0xBB, 0x02, 0x7E};
write(master_fd, test, 12);
while(!motors->commandAvailable()) {
}
MotorMessage mm;
mm = motors-> receiveCommand();
ASSERT_EQ(300, mm.getData());
ASSERT_EQ(MotorMessage::TYPE_WRITE, mm.getType());
ASSERT_EQ(MotorMessage::REG_LEFT_SPEED_SET, mm.getRegister());
}
TEST_F(MotorSerialTests, badReadFails){
uint8_t test[]= {0xdd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//uint8_t test[]= {0x7E, 0x02, 0xBB, 0x07, 0x00, 0x00, 0x01, 0x2C, 0x0E};
write(master_fd, test, 9);
ros::Rate loop(10);
int times = 0;
while(!motors->commandAvailable()) {
loop.sleep();
times++;
if(times >= 20) {
break;
}
}
if(times >= 20) {
SUCCEED();
}
else {
FAIL();
}
}
TEST_F(MotorSerialTests, writeWorks) {
MotorMessage version;
version.setRegister(MotorMessage::REG_FIRMWARE_VERSION);
version.setType(MotorMessage::TYPE_READ);
version.setData(0);
motors->transmitCommand(version);
uint8_t arr[9];
read(master_fd, arr, 9);
std::vector<uint8_t> input(arr, arr + sizeof(arr)/ sizeof(uint8_t));
ASSERT_EQ(input, version.serialize());
}
TEST_F(MotorSerialTests, writeMultipleWorks) {
std::vector<MotorMessage> commands;
MotorMessage left_odom;
left_odom.setRegister(MotorMessage::REG_LEFT_ODOM);
left_odom.setType(MotorMessage::TYPE_READ);
left_odom.setData(0);
commands.push_back(left_odom);
MotorMessage right_odom;
right_odom.setRegister(MotorMessage::REG_RIGHT_ODOM);
right_odom.setType(MotorMessage::TYPE_READ);
right_odom.setData(0);
commands.push_back(right_odom);
MotorMessage left_vel;
left_vel.setRegister(MotorMessage::REG_LEFT_SPEED_MEASURED);
left_vel.setType(MotorMessage::TYPE_READ);
left_vel.setData(0);
commands.push_back(left_vel);
MotorMessage right_vel;
right_vel.setRegister(MotorMessage::REG_RIGHT_SPEED_MEASURED);
right_vel.setType(MotorMessage::TYPE_READ);
right_vel.setData(0);
commands.push_back(right_vel);
motors->transmitCommands(commands);
uint8_t arr[36];
read(master_fd, arr, 36);
std::vector<uint8_t> input(arr, arr + sizeof(arr)/ sizeof(uint8_t));
std::vector<uint8_t> expected(0);
for (std::vector<MotorMessage>::iterator i = commands.begin(); i != commands.end(); ++i){
std::vector<uint8_t> serialized = i->serialize();
expected.insert(expected.end(), serialized.begin(), serialized.end());
}
ASSERT_EQ(expected, input);
}
int main(int argc, char **argv){
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2016 Intel Corporation. All Rights Reserved.
*
* 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, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "i965_test_fixture.h"
#include "i965_jpeg_test_data.h"
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
namespace JPEG {
class JPEGDecodeTest : public I965TestFixture
{
protected:
static const VAEntrypoint entrypoint = VAEntrypointVLD;
};
TEST_F(JPEGDecodeTest, Entrypoint)
{
VAConfigID config = VA_INVALID_ID;
ConfigAttribs attributes;
struct i965_driver_data *i965(*this);
ASSERT_PTR(i965);
if (HAS_JPEG_DECODING(i965)) {
config = createConfig(profile, entrypoint, attributes);
} else {
VAStatus status = i965_CreateConfig(
*this, profile, entrypoint, attributes.data(), attributes.size(),
&config);
EXPECT_STATUS_EQ(VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT, status);
EXPECT_INVALID_ID(config);
}
if (config != VA_INVALID_ID)
destroyConfig(config);
}
class FourCCTest
: public JPEGDecodeTest
, public ::testing::WithParamInterface<
std::tuple<TestPattern::SharedConst, const char*> >
{
protected:
virtual void SetUp()
{
JPEGDecodeTest::SetUp();
std::string sFourcc;
std::tie(testPattern, sFourcc) = GetParam();
ASSERT_PTR(testPattern.get()) << "Invalid test pattern parameter";
ASSERT_EQ(4u, sFourcc.size())
<< "Invalid fourcc parameter '" << sFourcc << "'";
unsigned fourcc = VA_FOURCC(
sFourcc[0], sFourcc[1], sFourcc[2], sFourcc[3]);
pd = testPattern->encoded(fourcc);
ASSERT_PTR(pd.get())
<< "Unhandled fourcc parameter '" << sFourcc << "'"
<< " = 0x" << std::hex << fourcc << std::dec;
ASSERT_EQ(fourcc, pd->fourcc);
}
void validateComponent(const uint8_t * const expect, const uint8_t * actual,
unsigned width, unsigned height, unsigned pitch, unsigned hsample = 1,
unsigned vsample = 1)
{
for (size_t row(0); row < (height / vsample); ++row) {
for (size_t col(0); col < (width / hsample); ++col) {
size_t aIdx = (row * pitch) + col;
size_t eIdx = (row * vsample * height) + (col * hsample);
std::vector<uint8_t> samples;
for (size_t i(0); i < vsample; ++i) {
for (size_t j(0); j < hsample; ++j) {
size_t sIdx = eIdx + (width * i) + j;
samples.push_back(expect[sIdx]);
}
}
const uint8_t eVal =
std::accumulate(samples.begin(), samples.end(), 0x00)
/ samples.size();
const uint8_t aVal = actual[aIdx];
SCOPED_TRACE(
::testing::Message() << std::endl
<< "\tRow = " << row << std::endl
<< "\tColumn = " << col << std::endl
<< "\tExpect = 0x"
<< std::hex << std::setfill('0') << std::setw(2)
<< (uint32_t)eVal << std::endl
<< "\tActual = 0x"
<< std::hex << std::setfill('0') << std::setw(2)
<< (uint32_t)aVal << std::dec);
EXPECT_NEAR(eVal, aVal, 0x02);
}
}
}
void validateImageOutput(const VAImage& image, const uint8_t * const output)
{
{
SCOPED_TRACE("Y Component\n");
validateComponent(
testPattern->decoded().data(), output + image.offsets[0],
image.width, image.height, image.pitches[0]);
}
{
SCOPED_TRACE("U Component\n");
validateComponent(
testPattern->decoded().data() + (image.width * image.height),
output + image.offsets[1], image.width, image.height,
image.pitches[1], pd->pparam.components[0].h_sampling_factor,
pd->pparam.components[0].v_sampling_factor);
}
{
SCOPED_TRACE("V Component\n");
validateComponent(
testPattern->decoded().data() + (image.width * image.height * 2),
output + image.offsets[2], image.width, image.height,
image.pitches[2], pd->pparam.components[0].h_sampling_factor,
pd->pparam.components[0].v_sampling_factor);
}
}
void printComponentDataTo(std::ostream& os, const uint8_t * const data,
unsigned w, unsigned h, unsigned pitch, unsigned hsample = 1,
unsigned vsample = 1)
{
const uint8_t *row = data;
for (unsigned i(0); i < (h/vsample); ++i) {
for (size_t j(0); j < (w/hsample); ++j) {
os << "0x" << std::hex << std::setfill('0') << std::setw(2)
<< (uint32_t)row[j] << ",";
}
os << std::endl;
row += pitch;
}
os << std::setw(0) << std::setfill(' ') << std::dec << std::endl;
}
void printImageOutputTo(std::ostream& os, const VAImage& image,
const uint8_t * const output)
{
printComponentDataTo(os, output + image.offsets[0], image.width,
image.height, image.pitches[0]); // Y
printComponentDataTo(os, output + image.offsets[1], image.width,
image.height, image.pitches[1],
pd->pparam.components[0].h_sampling_factor,
pd->pparam.components[0].v_sampling_factor); // U
printComponentDataTo(os, output + image.offsets[2], image.width,
image.height, image.pitches[2],
pd->pparam.components[0].h_sampling_factor,
pd->pparam.components[0].v_sampling_factor); // V
}
TestPattern::SharedConst testPattern;
PictureData::SharedConst pd;
};
#define ASSERT_NO_FAILURE(statement) \
statement; \
ASSERT_FALSE(HasFailure());
TEST_P(FourCCTest, Decode)
{
VAConfigAttrib a = { type:VAConfigAttribRTFormat, value:pd->format };
ConfigAttribs attribs(1, a);
ASSERT_NO_FAILURE(
Surfaces surfaces = createSurfaces(
pd->pparam.picture_width, pd->pparam.picture_height, pd->format));
ASSERT_NO_FAILURE(
VAConfigID config = createConfig(profile, entrypoint, attribs));
ASSERT_NO_FAILURE(
VAContextID context = createContext(
config, pd->pparam.picture_width, pd->pparam.picture_height, 0,
surfaces));
ASSERT_NO_FAILURE(
VABufferID sliceDataBufId = createBuffer(
context, VASliceDataBufferType, pd->sparam.slice_data_size, 1,
pd->slice.data()));
ASSERT_NO_FAILURE(
VABufferID sliceParamBufId = createBuffer(
context, VASliceParameterBufferType, sizeof(pd->sparam), 1,
&pd->sparam));
ASSERT_NO_FAILURE(
VABufferID picBufId = createBuffer(
context, VAPictureParameterBufferType, sizeof(pd->pparam), 1,
&pd->pparam));
ASSERT_NO_FAILURE(
VABufferID iqMatrixBufId = createBuffer(
context, VAIQMatrixBufferType, sizeof(IQMatrix), 1, &pd->iqmatrix));
ASSERT_NO_FAILURE(
VABufferID huffTableBufId = createBuffer(
context, VAHuffmanTableBufferType, sizeof(HuffmanTable), 1,
&pd->huffman));
ASSERT_NO_FAILURE(beginPicture(context, surfaces.front()));
ASSERT_NO_FAILURE(renderPicture(context, &picBufId));
ASSERT_NO_FAILURE(renderPicture(context, &iqMatrixBufId));
ASSERT_NO_FAILURE(renderPicture(context, &huffTableBufId));
ASSERT_NO_FAILURE(renderPicture(context, &sliceParamBufId));
ASSERT_NO_FAILURE(renderPicture(context, &sliceDataBufId));
ASSERT_NO_FAILURE(endPicture(context));
VAImage image;
ASSERT_NO_FAILURE(deriveImage(surfaces.front(), image));
ASSERT_NO_FAILURE(
uint8_t *output = mapBuffer<uint8_t>(image.buf));
unsigned rwidth = ALIGN(image.width, 128);
unsigned rheight =
ALIGN(image.height, 32)
+ ALIGN(image.height / pd->pparam.components[0].v_sampling_factor, 32)
* 2;
SCOPED_TRACE(
::testing::Message()
<< std::endl
<< "image : " << image.width << "x" << image.height
<< std::endl
<< "region : " << rwidth << "x" << rheight
<< std::endl
<< "planes : " << image.num_planes
<< std::endl
<< "offsets: " << image.offsets[0] << " " << image.offsets[1] << " " << image.offsets[2]
<< std::endl
<< "pitches: " << image.pitches[0] << " " << image.pitches[1] << " " << image.pitches[2]
);
EXPECT_EQ(3u, image.num_planes);
EXPECT_EQ(pd->pparam.picture_width, image.width);
EXPECT_EQ(pd->pparam.picture_height, image.height);
EXPECT_EQ(rwidth * rheight, image.data_size);
EXPECT_EQ(pd->fourcc, image.format.fourcc);
std::ostringstream oss;
printImageOutputTo(oss, image, output);
RecordProperty("Output", oss.str());
validateImageOutput(image, output);
// std::cout << oss.str();
unmapBuffer(image.buf);
destroyBuffer(huffTableBufId);
destroyBuffer(iqMatrixBufId);
destroyBuffer(picBufId);
destroyBuffer(sliceParamBufId);
destroyBuffer(sliceDataBufId);
destroyImage(image);
destroyContext(context);
destroyConfig(config);
destroySurfaces(surfaces);
}
/** Teach Google Test how to print a TestPattern::SharedConst object */
void PrintTo(const TestPattern::SharedConst& t, std::ostream* os)
{
*os << *t;
}
INSTANTIATE_TEST_CASE_P(
JPEG, FourCCTest,
::testing::Combine(
::testing::Values(
TestPattern::SharedConst(new TestPatternData<1>),
TestPattern::SharedConst(new TestPatternData<2>),
TestPattern::SharedConst(new TestPatternData<3>),
TestPattern::SharedConst(new TestPatternData<4>)
),
::testing::Values("IMC3", "422H", "422V", "444P", "411P"))
);
} // namespace JPEG
<commit_msg>test: skip jpeg fourcc decode test if unsupported by hw<commit_after>/*
* Copyright (C) 2016 Intel Corporation. All Rights Reserved.
*
* 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, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "i965_test_fixture.h"
#include "i965_jpeg_test_data.h"
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
namespace JPEG {
class JPEGDecodeTest : public I965TestFixture
{
protected:
static const VAEntrypoint entrypoint = VAEntrypointVLD;
};
TEST_F(JPEGDecodeTest, Entrypoint)
{
VAConfigID config = VA_INVALID_ID;
ConfigAttribs attributes;
struct i965_driver_data *i965(*this);
ASSERT_PTR(i965);
if (HAS_JPEG_DECODING(i965)) {
config = createConfig(profile, entrypoint, attributes);
} else {
VAStatus status = i965_CreateConfig(
*this, profile, entrypoint, attributes.data(), attributes.size(),
&config);
EXPECT_STATUS_EQ(VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT, status);
EXPECT_INVALID_ID(config);
}
if (config != VA_INVALID_ID)
destroyConfig(config);
}
class FourCCTest
: public JPEGDecodeTest
, public ::testing::WithParamInterface<
std::tuple<TestPattern::SharedConst, const char*> >
{
protected:
virtual void SetUp()
{
JPEGDecodeTest::SetUp();
std::string sFourcc;
std::tie(testPattern, sFourcc) = GetParam();
ASSERT_PTR(testPattern.get()) << "Invalid test pattern parameter";
ASSERT_EQ(4u, sFourcc.size())
<< "Invalid fourcc parameter '" << sFourcc << "'";
unsigned fourcc = VA_FOURCC(
sFourcc[0], sFourcc[1], sFourcc[2], sFourcc[3]);
pd = testPattern->encoded(fourcc);
ASSERT_PTR(pd.get())
<< "Unhandled fourcc parameter '" << sFourcc << "'"
<< " = 0x" << std::hex << fourcc << std::dec;
ASSERT_EQ(fourcc, pd->fourcc);
}
void validateComponent(const uint8_t * const expect, const uint8_t * actual,
unsigned width, unsigned height, unsigned pitch, unsigned hsample = 1,
unsigned vsample = 1)
{
for (size_t row(0); row < (height / vsample); ++row) {
for (size_t col(0); col < (width / hsample); ++col) {
size_t aIdx = (row * pitch) + col;
size_t eIdx = (row * vsample * height) + (col * hsample);
std::vector<uint8_t> samples;
for (size_t i(0); i < vsample; ++i) {
for (size_t j(0); j < hsample; ++j) {
size_t sIdx = eIdx + (width * i) + j;
samples.push_back(expect[sIdx]);
}
}
const uint8_t eVal =
std::accumulate(samples.begin(), samples.end(), 0x00)
/ samples.size();
const uint8_t aVal = actual[aIdx];
SCOPED_TRACE(
::testing::Message() << std::endl
<< "\tRow = " << row << std::endl
<< "\tColumn = " << col << std::endl
<< "\tExpect = 0x"
<< std::hex << std::setfill('0') << std::setw(2)
<< (uint32_t)eVal << std::endl
<< "\tActual = 0x"
<< std::hex << std::setfill('0') << std::setw(2)
<< (uint32_t)aVal << std::dec);
EXPECT_NEAR(eVal, aVal, 0x02);
}
}
}
void validateImageOutput(const VAImage& image, const uint8_t * const output)
{
{
SCOPED_TRACE("Y Component\n");
validateComponent(
testPattern->decoded().data(), output + image.offsets[0],
image.width, image.height, image.pitches[0]);
}
{
SCOPED_TRACE("U Component\n");
validateComponent(
testPattern->decoded().data() + (image.width * image.height),
output + image.offsets[1], image.width, image.height,
image.pitches[1], pd->pparam.components[0].h_sampling_factor,
pd->pparam.components[0].v_sampling_factor);
}
{
SCOPED_TRACE("V Component\n");
validateComponent(
testPattern->decoded().data() + (image.width * image.height * 2),
output + image.offsets[2], image.width, image.height,
image.pitches[2], pd->pparam.components[0].h_sampling_factor,
pd->pparam.components[0].v_sampling_factor);
}
}
void printComponentDataTo(std::ostream& os, const uint8_t * const data,
unsigned w, unsigned h, unsigned pitch, unsigned hsample = 1,
unsigned vsample = 1)
{
const uint8_t *row = data;
for (unsigned i(0); i < (h/vsample); ++i) {
for (size_t j(0); j < (w/hsample); ++j) {
os << "0x" << std::hex << std::setfill('0') << std::setw(2)
<< (uint32_t)row[j] << ",";
}
os << std::endl;
row += pitch;
}
os << std::setw(0) << std::setfill(' ') << std::dec << std::endl;
}
void printImageOutputTo(std::ostream& os, const VAImage& image,
const uint8_t * const output)
{
printComponentDataTo(os, output + image.offsets[0], image.width,
image.height, image.pitches[0]); // Y
printComponentDataTo(os, output + image.offsets[1], image.width,
image.height, image.pitches[1],
pd->pparam.components[0].h_sampling_factor,
pd->pparam.components[0].v_sampling_factor); // U
printComponentDataTo(os, output + image.offsets[2], image.width,
image.height, image.pitches[2],
pd->pparam.components[0].h_sampling_factor,
pd->pparam.components[0].v_sampling_factor); // V
}
TestPattern::SharedConst testPattern;
PictureData::SharedConst pd;
};
#define ASSERT_NO_FAILURE(statement) \
statement; \
ASSERT_FALSE(HasFailure());
TEST_P(FourCCTest, Decode)
{
struct i965_driver_data *i965(*this);
ASSERT_PTR(i965);
if (not HAS_JPEG_DECODING(i965)) {
RecordProperty("skipped", true);
std::cout << "[ SKIPPED ] " << getFullTestName()
<< " is unsupported on this hardware" << std::endl;
return;
}
VAConfigAttrib a = { type:VAConfigAttribRTFormat, value:pd->format };
ConfigAttribs attribs(1, a);
ASSERT_NO_FAILURE(
Surfaces surfaces = createSurfaces(
pd->pparam.picture_width, pd->pparam.picture_height, pd->format));
ASSERT_NO_FAILURE(
VAConfigID config = createConfig(profile, entrypoint, attribs));
ASSERT_NO_FAILURE(
VAContextID context = createContext(
config, pd->pparam.picture_width, pd->pparam.picture_height, 0,
surfaces));
ASSERT_NO_FAILURE(
VABufferID sliceDataBufId = createBuffer(
context, VASliceDataBufferType, pd->sparam.slice_data_size, 1,
pd->slice.data()));
ASSERT_NO_FAILURE(
VABufferID sliceParamBufId = createBuffer(
context, VASliceParameterBufferType, sizeof(pd->sparam), 1,
&pd->sparam));
ASSERT_NO_FAILURE(
VABufferID picBufId = createBuffer(
context, VAPictureParameterBufferType, sizeof(pd->pparam), 1,
&pd->pparam));
ASSERT_NO_FAILURE(
VABufferID iqMatrixBufId = createBuffer(
context, VAIQMatrixBufferType, sizeof(IQMatrix), 1, &pd->iqmatrix));
ASSERT_NO_FAILURE(
VABufferID huffTableBufId = createBuffer(
context, VAHuffmanTableBufferType, sizeof(HuffmanTable), 1,
&pd->huffman));
ASSERT_NO_FAILURE(beginPicture(context, surfaces.front()));
ASSERT_NO_FAILURE(renderPicture(context, &picBufId));
ASSERT_NO_FAILURE(renderPicture(context, &iqMatrixBufId));
ASSERT_NO_FAILURE(renderPicture(context, &huffTableBufId));
ASSERT_NO_FAILURE(renderPicture(context, &sliceParamBufId));
ASSERT_NO_FAILURE(renderPicture(context, &sliceDataBufId));
ASSERT_NO_FAILURE(endPicture(context));
VAImage image;
ASSERT_NO_FAILURE(deriveImage(surfaces.front(), image));
ASSERT_NO_FAILURE(
uint8_t *output = mapBuffer<uint8_t>(image.buf));
unsigned rwidth = ALIGN(image.width, 128);
unsigned rheight =
ALIGN(image.height, 32)
+ ALIGN(image.height / pd->pparam.components[0].v_sampling_factor, 32)
* 2;
SCOPED_TRACE(
::testing::Message()
<< std::endl
<< "image : " << image.width << "x" << image.height
<< std::endl
<< "region : " << rwidth << "x" << rheight
<< std::endl
<< "planes : " << image.num_planes
<< std::endl
<< "offsets: " << image.offsets[0] << " " << image.offsets[1] << " " << image.offsets[2]
<< std::endl
<< "pitches: " << image.pitches[0] << " " << image.pitches[1] << " " << image.pitches[2]
);
EXPECT_EQ(3u, image.num_planes);
EXPECT_EQ(pd->pparam.picture_width, image.width);
EXPECT_EQ(pd->pparam.picture_height, image.height);
EXPECT_EQ(rwidth * rheight, image.data_size);
EXPECT_EQ(pd->fourcc, image.format.fourcc);
std::ostringstream oss;
printImageOutputTo(oss, image, output);
RecordProperty("Output", oss.str());
validateImageOutput(image, output);
// std::cout << oss.str();
unmapBuffer(image.buf);
destroyBuffer(huffTableBufId);
destroyBuffer(iqMatrixBufId);
destroyBuffer(picBufId);
destroyBuffer(sliceParamBufId);
destroyBuffer(sliceDataBufId);
destroyImage(image);
destroyContext(context);
destroyConfig(config);
destroySurfaces(surfaces);
}
/** Teach Google Test how to print a TestPattern::SharedConst object */
void PrintTo(const TestPattern::SharedConst& t, std::ostream* os)
{
*os << *t;
}
INSTANTIATE_TEST_CASE_P(
JPEG, FourCCTest,
::testing::Combine(
::testing::Values(
TestPattern::SharedConst(new TestPatternData<1>),
TestPattern::SharedConst(new TestPatternData<2>),
TestPattern::SharedConst(new TestPatternData<3>),
TestPattern::SharedConst(new TestPatternData<4>)
),
::testing::Values("IMC3", "422H", "422V", "444P", "411P"))
);
} // namespace JPEG
<|endoftext|>
|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "fixedsourceselector.h"
#include "singlenumericattribute.hpp"
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.attribute.fixed_source_selector");
namespace search {
namespace {
attribute::Config getConfig() { return attribute::Config(attribute::BasicType::INT8); }
}
FixedSourceSelector::Iterator::Iterator(const FixedSourceSelector & sourceSelector) :
IIterator(sourceSelector._source),
_attributeGuard(sourceSelector._realSource)
{ }
FixedSourceSelector::FixedSourceSelector(queryeval::Source defaultSource,
const vespalib::string & attrBaseFileName,
uint32_t initialNumDocs) :
SourceSelector(defaultSource, AttributeVector::SP(new SourceStore(attrBaseFileName, getConfig()))),
_source(static_cast<SourceStore &>(*_realSource))
{
reserve(initialNumDocs);
_source.commit();
}
FixedSourceSelector::~FixedSourceSelector()
{
}
FixedSourceSelector::UP
FixedSourceSelector::cloneAndSubtract(const vespalib::string & attrBaseFileName,
uint32_t diff)
{
queryeval::Source newDefault = getNewSource(getDefaultSource(), diff);
FixedSourceSelector::UP selector(new FixedSourceSelector(newDefault, attrBaseFileName, _source.getNumDocs()-1));
for (uint32_t docId = 0; docId < _source.getNumDocs(); ++docId) {
queryeval::Source src = _source.get(docId);
src = getNewSource(src, diff);
assert(src < SOURCE_LIMIT);
selector->_source.set(docId, src);
}
selector->_source.commit();
selector->setBaseId(getBaseId() + diff);
selector->_source.setCommittedDocIdLimit(_source.getCommittedDocIdLimit());
return selector;
}
FixedSourceSelector::UP
FixedSourceSelector::load(const vespalib::string & baseFileName)
{
LoadInfo::UP info = extractLoadInfo(baseFileName);
info->load();
FixedSourceSelector::UP selector(new FixedSourceSelector(
info->header()._defaultSource,
info->header()._baseFileName,
0));
selector->setBaseId(info->header()._baseId);
selector->_source.load();
return selector;
}
void FixedSourceSelector::reserve(uint32_t numDocs)
{
const uint32_t maxDoc(_source.getNumDocs());
const uint32_t newMaxDocIdPlussOne(numDocs + 1);
if (newMaxDocIdPlussOne > maxDoc) {
uint32_t newDocId(0);
for (_source.addDoc(newDocId); newDocId < numDocs; _source.addDoc(newDocId));
for (uint32_t i = maxDoc; i < newMaxDocIdPlussOne; ++i) {
_source.set(i, getDefaultSource());
}
}
}
void
FixedSourceSelector::setSource(uint32_t docId, queryeval::Source source)
{
assert(source < SOURCE_LIMIT);
/**
* Due to matchingloop advancing 1 past end, we need to initialize data that
* far too.
**/
reserve(docId+1);
_source.update(docId, source);
_source.updateUncommittedDocIdLimit(docId + 1);
_source.commit();
}
void
FixedSourceSelector::compactLidSpace(uint32_t lidLimit)
{
_source.compactLidSpace(lidLimit + 1);
}
} // namespace search
<commit_msg>Don't compact lid space on source selector if wanted lid limit is higher than current limit. This can happen when none of the document fields are indexed.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "fixedsourceselector.h"
#include "singlenumericattribute.hpp"
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.attribute.fixed_source_selector");
namespace search {
namespace {
attribute::Config getConfig() { return attribute::Config(attribute::BasicType::INT8); }
}
FixedSourceSelector::Iterator::Iterator(const FixedSourceSelector & sourceSelector) :
IIterator(sourceSelector._source),
_attributeGuard(sourceSelector._realSource)
{ }
FixedSourceSelector::FixedSourceSelector(queryeval::Source defaultSource,
const vespalib::string & attrBaseFileName,
uint32_t initialNumDocs) :
SourceSelector(defaultSource, AttributeVector::SP(new SourceStore(attrBaseFileName, getConfig()))),
_source(static_cast<SourceStore &>(*_realSource))
{
reserve(initialNumDocs);
_source.commit();
}
FixedSourceSelector::~FixedSourceSelector()
{
}
FixedSourceSelector::UP
FixedSourceSelector::cloneAndSubtract(const vespalib::string & attrBaseFileName,
uint32_t diff)
{
queryeval::Source newDefault = getNewSource(getDefaultSource(), diff);
FixedSourceSelector::UP selector(new FixedSourceSelector(newDefault, attrBaseFileName, _source.getNumDocs()-1));
for (uint32_t docId = 0; docId < _source.getNumDocs(); ++docId) {
queryeval::Source src = _source.get(docId);
src = getNewSource(src, diff);
assert(src < SOURCE_LIMIT);
selector->_source.set(docId, src);
}
selector->_source.commit();
selector->setBaseId(getBaseId() + diff);
selector->_source.setCommittedDocIdLimit(_source.getCommittedDocIdLimit());
return selector;
}
FixedSourceSelector::UP
FixedSourceSelector::load(const vespalib::string & baseFileName)
{
LoadInfo::UP info = extractLoadInfo(baseFileName);
info->load();
FixedSourceSelector::UP selector(new FixedSourceSelector(
info->header()._defaultSource,
info->header()._baseFileName,
0));
selector->setBaseId(info->header()._baseId);
selector->_source.load();
return selector;
}
void FixedSourceSelector::reserve(uint32_t numDocs)
{
const uint32_t maxDoc(_source.getNumDocs());
const uint32_t newMaxDocIdPlussOne(numDocs + 1);
if (newMaxDocIdPlussOne > maxDoc) {
uint32_t newDocId(0);
for (_source.addDoc(newDocId); newDocId < numDocs; _source.addDoc(newDocId));
for (uint32_t i = maxDoc; i < newMaxDocIdPlussOne; ++i) {
_source.set(i, getDefaultSource());
}
}
}
void
FixedSourceSelector::setSource(uint32_t docId, queryeval::Source source)
{
assert(source < SOURCE_LIMIT);
/**
* Due to matchingloop advancing 1 past end, we need to initialize data that
* far too.
**/
reserve(docId+1);
_source.update(docId, source);
_source.updateUncommittedDocIdLimit(docId + 1);
_source.commit();
}
void
FixedSourceSelector::compactLidSpace(uint32_t lidLimit)
{
if (lidLimit < _source.getCommittedDocIdLimit()) {
_source.compactLidSpace(lidLimit + 1);
}
}
} // namespace search
<|endoftext|>
|
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2017 Ruben Van Boxem
*
* 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.
**/
/*
* Signal
* Registers observers.
* Notifies registered observers.
*/
#ifndef SKUI_CORE_SIGNAL_H
#define SKUI_CORE_SIGNAL_H
#include "core/slot.h++"
#include "core/trackable.h++"
#include "core/value_ptr.h++"
#include <algorithm>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <mutex>
#include <utility>
namespace skui
{
namespace core
{
namespace implementation
{
template<typename... ArgTypes>
class signal_base : public tracker
{
public:
using function_type = void(*)(ArgTypes...);
using slot_type = slot<void, ArgTypes...>;
using object_slot_type = std::pair<const trackable*, value_ptr<slot_type>>;
using connection_type = typename std::list<object_slot_type>::const_iterator;
signal_base() = default;
~signal_base() { disconnect_all(); }
signal_base(const signal_base& other)
: slots()
{
std::copy(other.slots.begin(), other.slots.end(), std::back_inserter(slots));
}
signal_base(signal_base&& other) : slots(std::move(other.slots)) {}
signal_base& operator=(signal_base other) { swap(slots, other.slots); return *this; }
virtual void trackable_deleted(const trackable* tracker) override
{
disconnect(tracker);
}
virtual void trackable_moved(const trackable* old_object, const trackable* new_object) override
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
std::for_each(slots.begin(), slots.end(),
[&old_object, &new_object](object_slot_type& object_slot)
{
if(object_slot.first == old_object)
object_slot.first = new_object;
});
}
virtual void trackable_copied(const trackable* old_object, const trackable* new_object) override
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
std::for_each(slots.begin(), slots.end(),
[&old_object, &new_object, this](const object_slot_type& object_slot)
{
if(object_slot.first == old_object)
slots.push_back({new_object, object_slot.second});
});
}
template<typename Callable, typename ReturnType = void>
connection_type connect(Callable&& callable)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
slots.emplace_back(nullptr, make_value<function_slot<Callable, ReturnType, ArgTypes...>>(callable));
return --slots.end();
}
template<typename Class, typename ReturnType>
connection_type connect(Class* object, ReturnType(Class::* slot)(ArgTypes...))
{
static_assert(std::is_base_of<trackable, Class>::value,
"You can only connect to member functions of a trackable object.");
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
slots.emplace_back(object, make_value<member_function_slot<Class, ReturnType, ArgTypes...>>(slot));
object->track(this);
return --slots.end();
}
template<typename Class, typename ReturnType>
connection_type connect(const Class* object, ReturnType(Class::* slot)(ArgTypes...) const)
{
static_assert(std::is_base_of<trackable, Class>::value,
"You can only connect to member functions of a trackable object");
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
object_slot_type object_slot(object, make_value<const_member_function_slot<Class, ReturnType, ArgTypes...>>(slot));
slots.emplace_back(std::move(object_slot));
object->track(this);
return --slots.end();
}
// connects first object like first object
void connect(trackable* /*first*/, trackable* /*second*/)
{
// trackable copy constructor makes second->track(this) unnecessary
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
}
// removes a previously made connection, handles lifetime tracking if it was the last connection to a specific object
void disconnect(connection_type connection)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
const trackable* object = connection->first;
slots.erase(connection);
if(object && std::find_if(slots.begin(), slots.end(),
[&object](const object_slot_type& object_slot)
{
return object_slot.first == object;
}) == slots.end())
object->untrack(this);
}
// removes all connections to an object
void disconnect(const trackable* object)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
object->untrack(this);
slots.remove_if([object](const object_slot_type& object_slot)
{
return object == object_slot.first;
});
}
// removes all connections
void disconnect_all()
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
for(object_slot_type& object_slot : slots)
{
auto trackable = object_slot.first;
if(trackable)
trackable->untrack(this);
}
slots.clear();
}
protected:
// mutable here allows to connect to a const object's signals
mutable std::list<object_slot_type> slots;
mutable std::mutex slots_mutex;
};
}
template<typename... ArgTypes>
class signal : public implementation::signal_base<ArgTypes...>
{
public:
signal() = default;
void emit(ArgTypes... arguments) const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& object_slot : this->slots)
{
(*object_slot.second)(object_slot.first, arguments...);
}
}
};
// Parameterless specialization
template<> class signal<> : public implementation::signal_base<>
{
public:
signal() = default;
void emit() const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& object_slot : this->slots)
{
(*object_slot.second)(object_slot.first);
}
}
};
}
}
#endif
<commit_msg>Use std::any_of instead of std::find(...) != end.<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2017 Ruben Van Boxem
*
* 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.
**/
/*
* Signal
* Registers observers.
* Notifies registered observers.
*/
#ifndef SKUI_CORE_SIGNAL_H
#define SKUI_CORE_SIGNAL_H
#include "core/slot.h++"
#include "core/trackable.h++"
#include "core/value_ptr.h++"
#include <algorithm>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <mutex>
#include <utility>
namespace skui
{
namespace core
{
namespace implementation
{
template<typename... ArgTypes>
class signal_base : public tracker
{
public:
using function_type = void(*)(ArgTypes...);
using slot_type = slot<void, ArgTypes...>;
using object_slot_type = std::pair<const trackable*, value_ptr<slot_type>>;
using connection_type = typename std::list<object_slot_type>::const_iterator;
signal_base() = default;
~signal_base() { disconnect_all(); }
signal_base(const signal_base& other)
: slots()
{
std::copy(other.slots.begin(), other.slots.end(), std::back_inserter(slots));
}
signal_base(signal_base&& other) : slots(std::move(other.slots)) {}
signal_base& operator=(signal_base other) { swap(slots, other.slots); return *this; }
virtual void trackable_deleted(const trackable* tracker) override
{
disconnect(tracker);
}
virtual void trackable_moved(const trackable* old_object, const trackable* new_object) override
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
std::for_each(slots.begin(), slots.end(),
[&old_object, &new_object](object_slot_type& object_slot)
{
if(object_slot.first == old_object)
object_slot.first = new_object;
});
}
virtual void trackable_copied(const trackable* old_object, const trackable* new_object) override
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
std::for_each(slots.begin(), slots.end(),
[&old_object, &new_object, this](const object_slot_type& object_slot)
{
if(object_slot.first == old_object)
slots.push_back({new_object, object_slot.second});
});
}
template<typename Callable, typename ReturnType = void>
connection_type connect(Callable&& callable)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
slots.emplace_back(nullptr, make_value<function_slot<Callable, ReturnType, ArgTypes...>>(callable));
return --slots.end();
}
template<typename Class, typename ReturnType>
connection_type connect(Class* object, ReturnType(Class::* slot)(ArgTypes...))
{
static_assert(std::is_base_of<trackable, Class>::value,
"You can only connect to member functions of a trackable object.");
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
slots.emplace_back(object, make_value<member_function_slot<Class, ReturnType, ArgTypes...>>(slot));
object->track(this);
return --slots.end();
}
template<typename Class, typename ReturnType>
connection_type connect(const Class* object, ReturnType(Class::* slot)(ArgTypes...) const)
{
static_assert(std::is_base_of<trackable, Class>::value,
"You can only connect to member functions of a trackable object");
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
object_slot_type object_slot(object, make_value<const_member_function_slot<Class, ReturnType, ArgTypes...>>(slot));
slots.emplace_back(std::move(object_slot));
object->track(this);
return --slots.end();
}
// connects first object like first object
void connect(trackable* /*first*/, trackable* /*second*/)
{
// trackable copy constructor makes second->track(this) unnecessary
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
}
// removes a previously made connection, handles lifetime tracking if it was the last connection to a specific object
void disconnect(connection_type connection)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
const trackable* object = connection->first;
slots.erase(connection);
if(object && std::any_of(slots.begin(), slots.end(),
[&object](const object_slot_type& object_slot)
{ return object_slot.first == object; }))
object->untrack(this);
}
// removes all connections to an object
void disconnect(const trackable* object)
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
object->untrack(this);
slots.remove_if([object](const object_slot_type& object_slot)
{
return object == object_slot.first;
});
}
// removes all connections
void disconnect_all()
{
const std::lock_guard<decltype(slots_mutex)> lock(slots_mutex);
for(object_slot_type& object_slot : slots)
{
auto trackable = object_slot.first;
if(trackable)
trackable->untrack(this);
}
slots.clear();
}
protected:
// mutable here allows to connect to a const object's signals
mutable std::list<object_slot_type> slots;
mutable std::mutex slots_mutex;
};
}
template<typename... ArgTypes>
class signal : public implementation::signal_base<ArgTypes...>
{
public:
signal() = default;
void emit(ArgTypes... arguments) const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& object_slot : this->slots)
{
(*object_slot.second)(object_slot.first, arguments...);
}
}
};
// Parameterless specialization
template<> class signal<> : public implementation::signal_base<>
{
public:
signal() = default;
void emit() const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& object_slot : this->slots)
{
(*object_slot.second)(object_slot.first);
}
}
};
}
}
#endif
<|endoftext|>
|
<commit_before>#include "../../../YaizuComLib/src/stkpl/StkPl.h"
#include "../../../YaizuComLib/src/commonfunc/StkObject.h"
#include "../../../YaizuComLib/src/stkwebapp/StkWebAppSend.h"
void TestGetUser(StkWebAppSend* StkWebAppSendObj)
{
{
StkPlPrintf("GetUser(admin) ... ");
int ResultCode = 0;
StkWebAppSendObj->SetAutholization("Bearer admin manager");
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/user/", NULL, &ResultCode);
if (ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkObject* ResUserObj = ResObj->GetFirstChildElement()->GetFirstChildElement();
if (ResUserObj == NULL || StkPlWcsCmp(ResUserObj->GetName(), L"User") != 0) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
delete ResObj;
}
{
StkPlPrintf("GetUser(admin + Method=OPTIONS) ... ");
int ResultCode = 0;
StkWebAppSendObj->SetAutholization("Bearer admin manager");
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_OPTIONS, "/api/user/", NULL, &ResultCode);
if (ResObj != NULL || ResultCode != 200) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
delete ResObj;
}
{
StkPlPrintf("GetUser(dummy) ... ");
int ResultCode = 0;
StkWebAppSendObj->SetAutholization("Bearer dummy dummy");
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/user/", NULL, &ResultCode);
if (ResultCode != 401) {
StkPlPrintf("[NG] Res=%d\n", ResultCode);
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
delete ResObj;
}
}
bool TestForGetApi(StkWebAppSend* StkWebAppSendObj, const char* Url, const char* Auth, StkObject* CompObj)
{
int ResultCode = 0;
StkWebAppSendObj->SetAutholization(Auth);
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, Url, NULL, &ResultCode);
if (ResultCode != 200) {
if (ResObj != NULL) {
delete ResObj;
}
return false;
}
if (ResObj->Contains(CompObj) == NULL) {
delete ResObj;
return false;
}
return true;
}
void TestNewAgentInfoNotificationNormal(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("New agent information notification (testagent) ... ");
int ResultCode = 0;
{
StkObject* NewObj = new StkObject(L"");
NewObj->AppendChildElement(new StkObject(L"Name", L"testagent"));
NewObj->AppendChildElement(new StkObject(L"Status", -980));
NewObj->AppendChildElement(new StkObject(L"StatusTime", L"00000000FFFFFFFF"));
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/agent/", NewObj, &ResultCode);
if (ResultCode != 200) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ResObj;
delete NewObj;
}
int ErrCode = 0;
StkObject* ReqObj = StkObject::CreateObjectFromJson(L"{ \"Data\" : {\"AgentInfo\" : {\"Name\":\"testagent\", \"Status\":-980, \"AcqTime\" : \"00000000ffffffff\"}}}", &ErrCode);
bool Result = TestForGetApi(StkWebAppSendObj, "/api/agent/", "Bearer admin manager", ReqObj);
if (Result != true) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ReqObj;
StkPlPrintf("[OK]\n");
}
void TestNewAgentInfoNotificationNull(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("New agent information notification (NULL) ... ");
int ResultCode = 0;
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/agent/", NULL, &ResultCode);
if (ResultCode != 400 || ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkObject* ChkObj = new StkObject(L"Code", 4203);
StkObject* FndObj = ResObj->Contains(ChkObj);
if (FndObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ChkObj;
StkPlPrintf("[OK]\n");
delete ResObj;
}
void TestNewAgentInfoNotificationNoAgentInfo(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("New agent information notification (no agent info) ... ");
int ResultCode = 0;
int ErrCode = 0;
StkObject* ReqObj = StkObject::CreateObjectFromJson(L"{\"XXX\" : {\"Name\":\"testagent\", \"Status\":-980}}", &ErrCode);
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/agent/", ReqObj, &ResultCode);
if (ResultCode != 400 || ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkObject* ChkObj = new StkObject(L"Code", 4201);
StkObject* FndObj = ResObj->Contains(ChkObj);
if (FndObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ChkObj;
StkPlPrintf("[OK]\n");
delete ReqObj;
delete ResObj;
}
void TestNewAgentInfoNotificationForbiddenChar(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("New agent information notification (invalid host name) ... ");
const wchar_t* HostName[] = { L"abc_xyz", L"あいうえお", L"hello!" };
wchar_t ReqStr[256] = L"";
for (int Loop = 0; Loop < 3; Loop++) {
StkPlSwPrintf(ReqStr, 256, L"{\"Name\":\"%ls\", \"Status\":-980}", HostName[Loop]);
int ResultCode = 0;
int ErrCode = 0;
StkObject* ReqObj = StkObject::CreateObjectFromJson(ReqStr, &ErrCode);
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/agent/", ReqObj, &ResultCode);
if (ResultCode != 400 || ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkObject* ChkObj = new StkObject(L"Code", 4205);
StkObject* FndObj = ResObj->Contains(ChkObj);
if (FndObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ChkObj;
delete ReqObj;
delete ResObj;
}
StkPlPrintf("[OK]\n");
}
void TestPostOperationStop(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("PostOperationStop ... ");
int ResultCode = 0;
StkObject* ReqObj = new StkObject(L"");
ReqObj->AppendChildElement(new StkObject(L"Operation", L"Stop"));
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/service/", ReqObj, &ResultCode);
delete ResObj;
StkPlPrintf("[OK]\n");
}
void TestGetCommand(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("Get Status Command ... ");
int ResultCode1 = 0;
StkObject* ResObj1 = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/statuscommand/aaa/", NULL, &ResultCode1);
if (ResultCode1 != 400) {
if (ResObj1 != NULL) {
delete ResObj1;
}
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
StkPlPrintf("Get Operation Command ... ");
int ResultCode2 = 0;
StkObject* ResObj2 = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/opcommand/aaa/", NULL, &ResultCode2);
if (ResultCode2 != 400) {
if (ResObj2 != NULL) {
delete ResObj2;
}
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
StkPlPrintf("Get Status/Operation Command (Result checking) ... ");
if (!ResObj1->Equals(ResObj2)) {
delete ResObj1;
delete ResObj2;
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
int ErrCode = 0;
StkObject *CodeObj = StkObject::CreateObjectFromJson(L"{\"Code\" : 4060}", &ErrCode);
if (!ResObj1->Contains(CodeObj) || !ResObj2->Contains(CodeObj)) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete CodeObj;
delete ResObj1;
delete ResObj2;
StkPlPrintf("[OK]\n");
}
void TestNewCommand(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("Add new Command ... ");
{
int ResultCode = 0;
int ErrCode = 0;
StkObject* ReqObj = StkObject::CreateObjectFromJson(L"{\"Name\" : \"hello\", \"Type\" : 0, \"Script\" : \"echo hello, world!!\", \"ServerFileName\" : \"\", \"AgentFileName\" : \"\"}", &ErrCode);
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/command/", ReqObj, &ResultCode);
if (ResultCode != 200) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
if (ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ReqObj;
delete ResObj;
}
{
int ResultCode = 0;
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/command/", NULL, &ResultCode);
if (ResultCode != 200) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
int ErrCode = 0;
StkObject* CompObj = StkObject::CreateObjectFromJson(L"\"Command\" : {\"Name\" : \"hello\"}", &ErrCode);
if (!ResObj->Contains(CompObj)) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete CompObj;
delete ResObj;
}
StkPlPrintf("[OK]\n");
}
int main(int Argc, char* Argv[])
{
StkPlSleepMs(3000);
StkWebAppSend* StkWebAppSendObj = new StkWebAppSend(10, L"localhost", 10009);
TestGetUser(StkWebAppSendObj);
TestNewAgentInfoNotificationNormal(StkWebAppSendObj);
TestNewAgentInfoNotificationNull(StkWebAppSendObj);
TestNewAgentInfoNotificationNoAgentInfo(StkWebAppSendObj);
TestNewAgentInfoNotificationForbiddenChar(StkWebAppSendObj);
TestGetCommand(StkWebAppSendObj);
TestNewCommand(StkWebAppSendObj);
TestPostOperationStop(StkWebAppSendObj);
delete StkWebAppSendObj;
return 0;
}
<commit_msg>#49 : Implementation : A bug fix of test code (StatusTime in post request has been changed into AcqTime)<commit_after>#include "../../../YaizuComLib/src/stkpl/StkPl.h"
#include "../../../YaizuComLib/src/commonfunc/StkObject.h"
#include "../../../YaizuComLib/src/stkwebapp/StkWebAppSend.h"
void TestGetUser(StkWebAppSend* StkWebAppSendObj)
{
{
StkPlPrintf("GetUser(admin) ... ");
int ResultCode = 0;
StkWebAppSendObj->SetAutholization("Bearer admin manager");
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/user/", NULL, &ResultCode);
if (ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkObject* ResUserObj = ResObj->GetFirstChildElement()->GetFirstChildElement();
if (ResUserObj == NULL || StkPlWcsCmp(ResUserObj->GetName(), L"User") != 0) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
delete ResObj;
}
{
StkPlPrintf("GetUser(admin + Method=OPTIONS) ... ");
int ResultCode = 0;
StkWebAppSendObj->SetAutholization("Bearer admin manager");
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_OPTIONS, "/api/user/", NULL, &ResultCode);
if (ResObj != NULL || ResultCode != 200) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
delete ResObj;
}
{
StkPlPrintf("GetUser(dummy) ... ");
int ResultCode = 0;
StkWebAppSendObj->SetAutholization("Bearer dummy dummy");
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/user/", NULL, &ResultCode);
if (ResultCode != 401) {
StkPlPrintf("[NG] Res=%d\n", ResultCode);
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
delete ResObj;
}
}
bool TestForGetApi(StkWebAppSend* StkWebAppSendObj, const char* Url, const char* Auth, StkObject* CompObj)
{
int ResultCode = 0;
StkWebAppSendObj->SetAutholization(Auth);
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, Url, NULL, &ResultCode);
if (ResultCode != 200) {
if (ResObj != NULL) {
delete ResObj;
}
return false;
}
if (ResObj->Contains(CompObj) == NULL) {
delete ResObj;
return false;
}
return true;
}
void TestNewAgentInfoNotificationNormal(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("New agent information notification (testagent) ... ");
int ResultCode = 0;
{
StkObject* NewObj = new StkObject(L"");
NewObj->AppendChildElement(new StkObject(L"Name", L"testagent"));
NewObj->AppendChildElement(new StkObject(L"Status", -980));
NewObj->AppendChildElement(new StkObject(L"AcqTime", L"00000000FFFFFFFF"));
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/agent/", NewObj, &ResultCode);
if (ResultCode != 200) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ResObj;
delete NewObj;
}
int ErrCode = 0;
StkObject* ReqObj = StkObject::CreateObjectFromJson(L"{ \"Data\" : {\"AgentInfo\" : {\"Name\":\"testagent\", \"Status\":-980, \"AcqTime\" : \"00000000ffffffff\"}}}", &ErrCode);
bool Result = TestForGetApi(StkWebAppSendObj, "/api/agent/", "Bearer admin manager", ReqObj);
if (Result != true) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ReqObj;
StkPlPrintf("[OK]\n");
}
void TestNewAgentInfoNotificationNull(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("New agent information notification (NULL) ... ");
int ResultCode = 0;
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/agent/", NULL, &ResultCode);
if (ResultCode != 400 || ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkObject* ChkObj = new StkObject(L"Code", 4203);
StkObject* FndObj = ResObj->Contains(ChkObj);
if (FndObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ChkObj;
StkPlPrintf("[OK]\n");
delete ResObj;
}
void TestNewAgentInfoNotificationNoAgentInfo(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("New agent information notification (no agent info) ... ");
int ResultCode = 0;
int ErrCode = 0;
StkObject* ReqObj = StkObject::CreateObjectFromJson(L"{\"XXX\" : {\"Name\":\"testagent\", \"Status\":-980}}", &ErrCode);
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/agent/", ReqObj, &ResultCode);
if (ResultCode != 400 || ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkObject* ChkObj = new StkObject(L"Code", 4201);
StkObject* FndObj = ResObj->Contains(ChkObj);
if (FndObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ChkObj;
StkPlPrintf("[OK]\n");
delete ReqObj;
delete ResObj;
}
void TestNewAgentInfoNotificationForbiddenChar(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("New agent information notification (invalid host name) ... ");
const wchar_t* HostName[] = { L"abc_xyz", L"あいうえお", L"hello!" };
wchar_t ReqStr[256] = L"";
for (int Loop = 0; Loop < 3; Loop++) {
StkPlSwPrintf(ReqStr, 256, L"{\"Name\":\"%ls\", \"Status\":-980}", HostName[Loop]);
int ResultCode = 0;
int ErrCode = 0;
StkObject* ReqObj = StkObject::CreateObjectFromJson(ReqStr, &ErrCode);
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/agent/", ReqObj, &ResultCode);
if (ResultCode != 400 || ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkObject* ChkObj = new StkObject(L"Code", 4205);
StkObject* FndObj = ResObj->Contains(ChkObj);
if (FndObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ChkObj;
delete ReqObj;
delete ResObj;
}
StkPlPrintf("[OK]\n");
}
void TestPostOperationStop(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("PostOperationStop ... ");
int ResultCode = 0;
StkObject* ReqObj = new StkObject(L"");
ReqObj->AppendChildElement(new StkObject(L"Operation", L"Stop"));
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/service/", ReqObj, &ResultCode);
delete ResObj;
StkPlPrintf("[OK]\n");
}
void TestGetCommand(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("Get Status Command ... ");
int ResultCode1 = 0;
StkObject* ResObj1 = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/statuscommand/aaa/", NULL, &ResultCode1);
if (ResultCode1 != 400) {
if (ResObj1 != NULL) {
delete ResObj1;
}
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
StkPlPrintf("Get Operation Command ... ");
int ResultCode2 = 0;
StkObject* ResObj2 = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/opcommand/aaa/", NULL, &ResultCode2);
if (ResultCode2 != 400) {
if (ResObj2 != NULL) {
delete ResObj2;
}
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
StkPlPrintf("[OK]\n");
StkPlPrintf("Get Status/Operation Command (Result checking) ... ");
if (!ResObj1->Equals(ResObj2)) {
delete ResObj1;
delete ResObj2;
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
int ErrCode = 0;
StkObject *CodeObj = StkObject::CreateObjectFromJson(L"{\"Code\" : 4060}", &ErrCode);
if (!ResObj1->Contains(CodeObj) || !ResObj2->Contains(CodeObj)) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete CodeObj;
delete ResObj1;
delete ResObj2;
StkPlPrintf("[OK]\n");
}
void TestNewCommand(StkWebAppSend* StkWebAppSendObj)
{
StkPlPrintf("Add new Command ... ");
{
int ResultCode = 0;
int ErrCode = 0;
StkObject* ReqObj = StkObject::CreateObjectFromJson(L"{\"Name\" : \"hello\", \"Type\" : 0, \"Script\" : \"echo hello, world!!\", \"ServerFileName\" : \"\", \"AgentFileName\" : \"\"}", &ErrCode);
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_POST, "/api/command/", ReqObj, &ResultCode);
if (ResultCode != 200) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
if (ResObj == NULL) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete ReqObj;
delete ResObj;
}
{
int ResultCode = 0;
StkObject* ResObj = StkWebAppSendObj->SendRequestRecvResponse(StkWebAppSend::STKWEBAPP_METHOD_GET, "/api/command/", NULL, &ResultCode);
if (ResultCode != 200) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
int ErrCode = 0;
StkObject* CompObj = StkObject::CreateObjectFromJson(L"\"Command\" : {\"Name\" : \"hello\"}", &ErrCode);
if (!ResObj->Contains(CompObj)) {
StkPlPrintf("[NG]\n");
StkPlExit(1);
}
delete CompObj;
delete ResObj;
}
StkPlPrintf("[OK]\n");
}
int main(int Argc, char* Argv[])
{
StkPlSleepMs(3000);
StkWebAppSend* StkWebAppSendObj = new StkWebAppSend(10, L"localhost", 10009);
TestGetUser(StkWebAppSendObj);
TestNewAgentInfoNotificationNormal(StkWebAppSendObj);
TestNewAgentInfoNotificationNull(StkWebAppSendObj);
TestNewAgentInfoNotificationNoAgentInfo(StkWebAppSendObj);
TestNewAgentInfoNotificationForbiddenChar(StkWebAppSendObj);
TestGetCommand(StkWebAppSendObj);
TestNewCommand(StkWebAppSendObj);
TestPostOperationStop(StkWebAppSendObj);
delete StkWebAppSendObj;
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file example.cpp
* @author Marcus Edel
*
* Simple random agent.
*/
#include <iostream>
#include "environment.hpp"
using namespace gym;
int main(int argc, char* argv[])
{
const std::string environment = "CartPole-v0";
const std::string host = "kurg.org";
const std::string port = "4040";
double totalReward = 0;
size_t totalSteps = 0;
Environment env(host, port, environment);
env.compression(9);
env.monitor.start("./dummy/", true, true);
env.reset();
env.render();
while (1)
{
arma::mat action = env.action_space.sample();
std::cout << "action: \n" << action << std::endl;
env.step(action);
totalReward += env.reward;
totalSteps += 1;
if (env.done)
{
break;
}
std::cout << "Current step: " << totalSteps << " current reward: "
<< totalReward << std::endl;
}
std::cout << "Instance: " << env.instance << " total steps: " << totalSteps
<< " reward: " << totalReward << std::endl;
std::cout << "Video: https://kurg.org/media/gym/" << env.instance
<< " (it might take some minutes before the video is accessible)."
<< std::endl;
return 0;
}
<commit_msg>Changed the host's default address<commit_after>/**
* @file example.cpp
* @author Marcus Edel
*
* Simple random agent.
*/
#include <iostream>
#include "environment.hpp"
using namespace gym;
int main(int argc, char* argv[])
{
const std::string environment = "CartPole-v0";
const std::string host = "127.0.0.1";
const std::string port = "4040";
double totalReward = 0;
size_t totalSteps = 0;
Environment env(host, port, environment);
env.compression(9);
env.monitor.start("./dummy/", true, true);
env.reset();
env.render();
while (1)
{
arma::mat action = env.action_space.sample();
std::cout << "action: \n" << action << std::endl;
env.step(action);
totalReward += env.reward;
totalSteps += 1;
if (env.done)
{
break;
}
std::cout << "Current step: " << totalSteps << " current reward: "
<< totalReward << std::endl;
}
std::cout << "Instance: " << env.instance << " total steps: " << totalSteps
<< " reward: " << totalReward << std::endl;
std::cout << "Video: https://kurg.org/media/gym/" << env.instance
<< " (it might take some minutes before the video is accessible)."
<< std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
LuaMan luaMan;
extern MatrixStack luaMatrixStack;
LuaBindFuncContainer& GetLuaBindFuncContainer()
{
static LuaBindFuncContainer c;
return c;
}
LuaMan::LuaMan()
{
L = nullptr;
}
LuaMan::~LuaMan()
{
assert(!L);
}
void LuaMan::Create()
{
Destroy();
L = luaL_newstate();
LuaBind(L);
for (auto it : GetLuaBindFuncContainer()) {
it(L);
}
#ifdef _DEBUG
const char* start = "lua/startD.lua";
#else
const char* start = "lua/start.lua";
#endif
if (!aflDoFile(L, start)) {
printf("%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
}
void LuaMan::Destroy()
{
if (!L) {
return;
}
int top = lua_gettop(L);
if (top > 0) {
aflog("error! stack is not empty\n");
}
lua_close(L);
L = nullptr;
}
void LuaMan::CallGlobal(const char* func)
{
luaMatrixStack.Reset();
lua_getglobal(L, func);
// aflDumpStack();
lua_call(L, 0, 0);
// aflDumpStack();
int top = lua_gettop(L);
if (top > 0) {
aflog("error! stack is not empty\n");
}
luaMatrixStack.Reset();
}
void LuaMan::Update()
{
CallGlobal("Update");
}
void LuaMan::Draw2D()
{
CallGlobal("Draw2D");
}
void LuaMan::Draw3D()
{
CallGlobal("Draw3D");
}
<commit_msg>Print error messages from Lua<commit_after>#include "stdafx.h"
LuaMan luaMan;
extern MatrixStack luaMatrixStack;
LuaBindFuncContainer& GetLuaBindFuncContainer()
{
static LuaBindFuncContainer c;
return c;
}
LuaMan::LuaMan()
{
L = nullptr;
}
LuaMan::~LuaMan()
{
assert(!L);
}
void LuaMan::Create()
{
Destroy();
L = luaL_newstate();
LuaBind(L);
for (auto it : GetLuaBindFuncContainer()) {
it(L);
}
#ifdef _DEBUG
const char* start = "lua/startD.lua";
#else
const char* start = "lua/start.lua";
#endif
if (!aflDoFile(L, start)) {
printf("%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
}
void LuaMan::Destroy()
{
if (!L) {
return;
}
int top = lua_gettop(L);
if (top > 0) {
aflog("error! stack is not empty\n");
}
lua_close(L);
L = nullptr;
}
void LuaMan::CallGlobal(const char* func)
{
luaMatrixStack.Reset();
lua_getglobal(L, func);
// aflDumpStack();
if (lua_pcall(L, 0, LUA_MULTRET, 0)) {
printf("%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
}
// aflDumpStack();
int top = lua_gettop(L);
if (top > 0) {
aflog("error! stack is not empty\n");
}
luaMatrixStack.Reset();
}
void LuaMan::Update()
{
CallGlobal("Update");
}
void LuaMan::Draw2D()
{
CallGlobal("Draw2D");
}
void LuaMan::Draw3D()
{
CallGlobal("Draw3D");
}
<|endoftext|>
|
<commit_before>/* Copyright 2019 Google LLC. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "block_map.h"
#include "third_party/gemmlowp/profiling/instrumentation.h"
#include "check_macros.h"
#include "opt_set.h"
#include "size_util.h"
namespace ruy {
void GetBlockByIndex(const BlockMap& block_map, int index,
SidePair<int>* block) {
gemmlowp::ScopedProfilingLabel label("GetBlockByIndex");
const std::uint32_t index_u32 = index;
const std::uint32_t rectr =
index_u32 & ((1u << block_map.rectangularness_log2[Side::kLhs]) - 1);
const std::uint32_t rectc =
index_u32 & ((1u << block_map.rectangularness_log2[Side::kRhs]) - 1);
const std::uint32_t n1 =
index_u32 >> (block_map.rectangularness_log2[Side::kLhs] +
block_map.rectangularness_log2[Side::kRhs]);
RUY_DCHECK_EQ(index_u32,
(n1 << (block_map.rectangularness_log2[Side::kLhs] +
block_map.rectangularness_log2[Side::kRhs])) +
rectr + rectc);
std::uint32_t br, bc;
if (block_map.traversal_order == BlockMapTraversalOrder::kLinear) {
br = n1 & ((1u << block_map.num_blocks_base_log2) - 1);
bc = n1 >> block_map.num_blocks_base_log2;
} else {
// Decode fractal z-order
const std::uint32_t n2 = (n1 & 0x99999999u) | ((n1 & 0x44444444u) >> 1) |
((n1 & 0x22222222u) << 1);
const std::uint32_t n4 = (n2 & 0xc3c3c3c3u) | ((n2 & 0x30303030u) >> 2) |
((n2 & 0x0c0c0c0cu) << 2);
const std::uint32_t n8 = (n4 & 0xf00ff00fu) | ((n4 & 0x0f000f00u) >> 4) |
((n4 & 0x00f000f0u) << 4);
const std::uint32_t n16 = (n8 & 0xff0000ffu) | ((n8 & 0x00ff0000u) >> 8) |
((n8 & 0x0000ff00u) << 8);
br = n16 & 0xffff;
bc = n16 >> 16;
if (block_map.traversal_order == BlockMapTraversalOrder::kFractalU) {
// Change fractal z-order to u-order
br ^= bc;
}
}
br = (br << block_map.rectangularness_log2[Side::kLhs]) + rectr;
bc = (bc << block_map.rectangularness_log2[Side::kRhs]) + rectc;
// Store
(*block)[Side::kLhs] = br;
(*block)[Side::kRhs] = bc;
}
namespace {
int floor_log2_quotient(int num, int denom) {
if (num <= denom) {
return 0;
}
int log2_quotient = floor_log2(num) - ceil_log2(denom);
if ((denom << (log2_quotient + 1)) <= num) {
log2_quotient++;
}
return log2_quotient;
}
} // namespace
void MakeBlockMap(int rows, int cols, int depth, int kernel_rows,
int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,
int cache_friendly_traversal_threshold, BlockMap* block_map) {
gemmlowp::ScopedProfilingLabel label("MakeBlockMap");
RUY_DCHECK_GE(rows, kernel_rows);
RUY_DCHECK_GE(cols, kernel_cols);
block_map->traversal_order = BlockMapTraversalOrder::kLinear;
if (RUY_OPT_ENABLED(RUY_OPT_FRACTAL) &&
(rows * lhs_scalar_size + cols * rhs_scalar_size) * depth >=
cache_friendly_traversal_threshold) {
block_map->traversal_order = RUY_OPT_ENABLED(RUY_OPT_FRACTAL_U)
? BlockMapTraversalOrder::kFractalU
: BlockMapTraversalOrder::kFractalZ;
}
// See the comment on BlockMap in block_map.h.
// The destination matrix shape (rows x cols) is to be subdivided into a
// square (N x N) grid of blocks, whose shapes must be multiples of the
// kernel block shape (kernel_rows x kernel_cols).
// Inside each of these N*N blocks, we may have one further level of
// subdivision either along rows or along cols but not both, to handle
// better the highly rectangular cases. That is what we call
// 'rectangularness'. This extra level of subdivision is into
// (1 << rows_rectangularness_log2) blocks along rows dimension, or into
// (1 << cols_rectangularness_log2) blocks along cols dimension.
int rows_rectangularness_log2 = 0;
int cols_rectangularness_log2 = 0;
// In order to compute these rectangularness values, we need to divide
// the destination matrix's aspect ratio,
// rows / cols
// by the kernel block's aspect ratio,
// kernel_block_rows / kernel_block_cols.
// The quotient of these two quotients simplifies to
// (rows * kernel_cols) / (cols * kernel_rows)
// Whence the introduction of the following products:
const int rows_times_kernel_cols = rows * kernel_cols;
const int cols_times_kernel_rows = cols * kernel_rows;
if (rows_times_kernel_cols > cols_times_kernel_rows) {
rows_rectangularness_log2 =
floor_log2_quotient(rows_times_kernel_cols, cols_times_kernel_rows);
// Sanity check that we did not over-estimate rows_rectangularness_log2.
RUY_DCHECK_GE(rows_times_kernel_cols >> rows_rectangularness_log2,
cols_times_kernel_rows);
} else if (cols_times_kernel_rows > rows_times_kernel_cols) {
cols_rectangularness_log2 =
floor_log2_quotient(cols_times_kernel_rows, rows_times_kernel_cols);
// Sanity check that we did not over-estimate cols_rectangularness_log2.
RUY_DCHECK_GE(cols_times_kernel_rows >> cols_rectangularness_log2,
rows_times_kernel_cols);
}
RUY_DCHECK(!rows_rectangularness_log2 || !cols_rectangularness_log2);
const int size = std::min(rows, cols);
const int size_floor_log2 = floor_log2(size);
const int depth_ceil_log2 = ceil_log2(depth);
const int kernel_width_log2 = ceil_log2(std::max(kernel_cols, kernel_rows));
// l1_size_log2 was originally, coarsely speaking the number of rows of LHS,
// or the number of columns of RHS in a matrix multiplication that we expect,
// to fit in L1 cache.
//
// This initial rationale is not necessarily still relevant. The logic below
// was determined empirically, not in a principled way.
int l1_size_log2;
if (size_floor_log2 <= 3) {
l1_size_log2 = size_floor_log2;
} else if (size_floor_log2 <= 6) {
l1_size_log2 = 4;
} else {
l1_size_log2 = 5;
}
// The 15 here implicitly encodes target a 32k L1 cache (2^15 == 32k).
// Once again this only has a distant memory of being originally motivated
// by such clear principles linking this logic to cache sizes.
l1_size_log2 = std::min(
l1_size_log2, 15 - depth_ceil_log2 -
ceil_log2(std::max(lhs_scalar_size, rhs_scalar_size)));
l1_size_log2 = std::max(l1_size_log2, kernel_width_log2);
l1_size_log2 = std::min(l1_size_log2, size_floor_log2);
int num_blocks_base_log2 = size_floor_log2 - l1_size_log2;
RUY_DCHECK_GE(num_blocks_base_log2, 0);
if (num_blocks_base_log2 == 0) {
if ((rows % kernel_rows) || (cols % kernel_cols)) {
num_blocks_base_log2 = 1;
}
}
int rows_rounded_up = round_up_pot(rows, kernel_rows);
int cols_rounded_up = round_up_pot(cols, kernel_cols);
const int num_blocks_of_rows_log2 =
num_blocks_base_log2 + rows_rectangularness_log2;
const int num_blocks_of_cols_log2 =
num_blocks_base_log2 + cols_rectangularness_log2;
const int smallr =
round_down_pot(rows_rounded_up >> num_blocks_of_rows_log2, kernel_rows);
const int smallc =
round_down_pot(cols_rounded_up >> num_blocks_of_cols_log2, kernel_cols);
const int missr =
round_up_pot(rows_rounded_up - (smallr << num_blocks_of_rows_log2),
kernel_rows) /
kernel_rows;
const int missc =
round_up_pot(cols_rounded_up - (smallc << num_blocks_of_cols_log2),
kernel_cols) /
kernel_cols;
block_map->dims[Side::kLhs] = rows;
block_map->dims[Side::kRhs] = cols;
block_map->kernel_dims[Side::kLhs] = kernel_rows;
block_map->kernel_dims[Side::kRhs] = kernel_cols;
block_map->num_blocks_base_log2 = num_blocks_base_log2;
block_map->rectangularness_log2[Side::kLhs] = rows_rectangularness_log2;
block_map->rectangularness_log2[Side::kRhs] = cols_rectangularness_log2;
block_map->small_block_dims[Side::kLhs] = smallr;
block_map->small_block_dims[Side::kRhs] = smallc;
block_map->large_blocks[Side::kLhs] = missr;
block_map->large_blocks[Side::kRhs] = missc;
}
void GetBlockMatrixCoords(Side side, const BlockMap& block_map,
const SidePair<int>& block, int* start, int* end) {
gemmlowp::ScopedProfilingLabel label("GetBlockMatrixCoords");
const int b = block[side];
*start =
b * block_map.small_block_dims[side] +
std::min(b, block_map.large_blocks[side]) * block_map.kernel_dims[side];
*end = *start + block_map.small_block_dims[side] +
(b < block_map.large_blocks[side] ? block_map.kernel_dims[side] : 0);
RUY_DCHECK_EQ(0, *start % block_map.kernel_dims[side]);
RUY_DCHECK_EQ(0, *end % block_map.kernel_dims[side]);
RUY_DCHECK_LE(*end, block_map.dims[side]);
RUY_DCHECK_LT(*start, *end);
RUY_DCHECK_GE(*start, 0);
}
void GetBlockMatrixCoords(const BlockMap& block_map, const SidePair<int>& block,
SidePair<int>* start, SidePair<int>* end) {
for (Side side : {Side::kLhs, Side::kRhs}) {
GetBlockMatrixCoords(side, block_map, block, &(*start)[side],
&(*end)[side]);
}
}
} // namespace ruy
<commit_msg>Remove a useless piece of code in MakeBlockMap. It was a remnant from when ruy was trying to skip the packing phase in some cases, letting kernels operate directly on source matrices. In that case, there was a difficulty if the matrix sizes were not multiples of kernel size and there was only one block.<commit_after>/* Copyright 2019 Google LLC. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "block_map.h"
#include "third_party/gemmlowp/profiling/instrumentation.h"
#include "check_macros.h"
#include "opt_set.h"
#include "size_util.h"
namespace ruy {
void GetBlockByIndex(const BlockMap& block_map, int index,
SidePair<int>* block) {
gemmlowp::ScopedProfilingLabel label("GetBlockByIndex");
const std::uint32_t index_u32 = index;
const std::uint32_t rectr =
index_u32 & ((1u << block_map.rectangularness_log2[Side::kLhs]) - 1);
const std::uint32_t rectc =
index_u32 & ((1u << block_map.rectangularness_log2[Side::kRhs]) - 1);
const std::uint32_t n1 =
index_u32 >> (block_map.rectangularness_log2[Side::kLhs] +
block_map.rectangularness_log2[Side::kRhs]);
RUY_DCHECK_EQ(index_u32,
(n1 << (block_map.rectangularness_log2[Side::kLhs] +
block_map.rectangularness_log2[Side::kRhs])) +
rectr + rectc);
std::uint32_t br, bc;
if (block_map.traversal_order == BlockMapTraversalOrder::kLinear) {
br = n1 & ((1u << block_map.num_blocks_base_log2) - 1);
bc = n1 >> block_map.num_blocks_base_log2;
} else {
// Decode fractal z-order
const std::uint32_t n2 = (n1 & 0x99999999u) | ((n1 & 0x44444444u) >> 1) |
((n1 & 0x22222222u) << 1);
const std::uint32_t n4 = (n2 & 0xc3c3c3c3u) | ((n2 & 0x30303030u) >> 2) |
((n2 & 0x0c0c0c0cu) << 2);
const std::uint32_t n8 = (n4 & 0xf00ff00fu) | ((n4 & 0x0f000f00u) >> 4) |
((n4 & 0x00f000f0u) << 4);
const std::uint32_t n16 = (n8 & 0xff0000ffu) | ((n8 & 0x00ff0000u) >> 8) |
((n8 & 0x0000ff00u) << 8);
br = n16 & 0xffff;
bc = n16 >> 16;
if (block_map.traversal_order == BlockMapTraversalOrder::kFractalU) {
// Change fractal z-order to u-order
br ^= bc;
}
}
br = (br << block_map.rectangularness_log2[Side::kLhs]) + rectr;
bc = (bc << block_map.rectangularness_log2[Side::kRhs]) + rectc;
// Store
(*block)[Side::kLhs] = br;
(*block)[Side::kRhs] = bc;
}
namespace {
int floor_log2_quotient(int num, int denom) {
if (num <= denom) {
return 0;
}
int log2_quotient = floor_log2(num) - ceil_log2(denom);
if ((denom << (log2_quotient + 1)) <= num) {
log2_quotient++;
}
return log2_quotient;
}
} // namespace
void MakeBlockMap(int rows, int cols, int depth, int kernel_rows,
int kernel_cols, int lhs_scalar_size, int rhs_scalar_size,
int cache_friendly_traversal_threshold, BlockMap* block_map) {
gemmlowp::ScopedProfilingLabel label("MakeBlockMap");
RUY_DCHECK_GE(rows, kernel_rows);
RUY_DCHECK_GE(cols, kernel_cols);
block_map->traversal_order = BlockMapTraversalOrder::kLinear;
if (RUY_OPT_ENABLED(RUY_OPT_FRACTAL) &&
(rows * lhs_scalar_size + cols * rhs_scalar_size) * depth >=
cache_friendly_traversal_threshold) {
block_map->traversal_order = RUY_OPT_ENABLED(RUY_OPT_FRACTAL_U)
? BlockMapTraversalOrder::kFractalU
: BlockMapTraversalOrder::kFractalZ;
}
// See the comment on BlockMap in block_map.h.
// The destination matrix shape (rows x cols) is to be subdivided into a
// square (N x N) grid of blocks, whose shapes must be multiples of the
// kernel block shape (kernel_rows x kernel_cols).
// Inside each of these N*N blocks, we may have one further level of
// subdivision either along rows or along cols but not both, to handle
// better the highly rectangular cases. That is what we call
// 'rectangularness'. This extra level of subdivision is into
// (1 << rows_rectangularness_log2) blocks along rows dimension, or into
// (1 << cols_rectangularness_log2) blocks along cols dimension.
int rows_rectangularness_log2 = 0;
int cols_rectangularness_log2 = 0;
// In order to compute these rectangularness values, we need to divide
// the destination matrix's aspect ratio,
// rows / cols
// by the kernel block's aspect ratio,
// kernel_block_rows / kernel_block_cols.
// The quotient of these two quotients simplifies to
// (rows * kernel_cols) / (cols * kernel_rows)
// Whence the introduction of the following products:
const int rows_times_kernel_cols = rows * kernel_cols;
const int cols_times_kernel_rows = cols * kernel_rows;
if (rows_times_kernel_cols > cols_times_kernel_rows) {
rows_rectangularness_log2 =
floor_log2_quotient(rows_times_kernel_cols, cols_times_kernel_rows);
// Sanity check that we did not over-estimate rows_rectangularness_log2.
RUY_DCHECK_GE(rows_times_kernel_cols >> rows_rectangularness_log2,
cols_times_kernel_rows);
} else if (cols_times_kernel_rows > rows_times_kernel_cols) {
cols_rectangularness_log2 =
floor_log2_quotient(cols_times_kernel_rows, rows_times_kernel_cols);
// Sanity check that we did not over-estimate cols_rectangularness_log2.
RUY_DCHECK_GE(cols_times_kernel_rows >> cols_rectangularness_log2,
rows_times_kernel_cols);
}
RUY_DCHECK(!rows_rectangularness_log2 || !cols_rectangularness_log2);
const int size = std::min(rows, cols);
const int size_floor_log2 = floor_log2(size);
const int depth_ceil_log2 = ceil_log2(depth);
const int kernel_width_log2 = ceil_log2(std::max(kernel_cols, kernel_rows));
// l1_size_log2 was originally, coarsely speaking the number of rows of LHS,
// or the number of columns of RHS in a matrix multiplication that we expect,
// to fit in L1 cache.
//
// This initial rationale is not necessarily still relevant. The logic below
// was determined empirically, not in a principled way.
int l1_size_log2;
if (size_floor_log2 <= 3) {
l1_size_log2 = size_floor_log2;
} else if (size_floor_log2 <= 6) {
l1_size_log2 = 4;
} else {
l1_size_log2 = 5;
}
// The 15 here implicitly encodes target a 32k L1 cache (2^15 == 32k).
// Once again this only has a distant memory of being originally motivated
// by such clear principles linking this logic to cache sizes.
l1_size_log2 = std::min(
l1_size_log2, 15 - depth_ceil_log2 -
ceil_log2(std::max(lhs_scalar_size, rhs_scalar_size)));
l1_size_log2 = std::max(l1_size_log2, kernel_width_log2);
l1_size_log2 = std::min(l1_size_log2, size_floor_log2);
int num_blocks_base_log2 = size_floor_log2 - l1_size_log2;
RUY_DCHECK_GE(num_blocks_base_log2, 0);
int rows_rounded_up = round_up_pot(rows, kernel_rows);
int cols_rounded_up = round_up_pot(cols, kernel_cols);
const int num_blocks_of_rows_log2 =
num_blocks_base_log2 + rows_rectangularness_log2;
const int num_blocks_of_cols_log2 =
num_blocks_base_log2 + cols_rectangularness_log2;
const int smallr =
round_down_pot(rows_rounded_up >> num_blocks_of_rows_log2, kernel_rows);
const int smallc =
round_down_pot(cols_rounded_up >> num_blocks_of_cols_log2, kernel_cols);
const int missr =
round_up_pot(rows_rounded_up - (smallr << num_blocks_of_rows_log2),
kernel_rows) /
kernel_rows;
const int missc =
round_up_pot(cols_rounded_up - (smallc << num_blocks_of_cols_log2),
kernel_cols) /
kernel_cols;
block_map->dims[Side::kLhs] = rows;
block_map->dims[Side::kRhs] = cols;
block_map->kernel_dims[Side::kLhs] = kernel_rows;
block_map->kernel_dims[Side::kRhs] = kernel_cols;
block_map->num_blocks_base_log2 = num_blocks_base_log2;
block_map->rectangularness_log2[Side::kLhs] = rows_rectangularness_log2;
block_map->rectangularness_log2[Side::kRhs] = cols_rectangularness_log2;
block_map->small_block_dims[Side::kLhs] = smallr;
block_map->small_block_dims[Side::kRhs] = smallc;
block_map->large_blocks[Side::kLhs] = missr;
block_map->large_blocks[Side::kRhs] = missc;
}
void GetBlockMatrixCoords(Side side, const BlockMap& block_map,
const SidePair<int>& block, int* start, int* end) {
gemmlowp::ScopedProfilingLabel label("GetBlockMatrixCoords");
const int b = block[side];
*start =
b * block_map.small_block_dims[side] +
std::min(b, block_map.large_blocks[side]) * block_map.kernel_dims[side];
*end = *start + block_map.small_block_dims[side] +
(b < block_map.large_blocks[side] ? block_map.kernel_dims[side] : 0);
RUY_DCHECK_EQ(0, *start % block_map.kernel_dims[side]);
RUY_DCHECK_EQ(0, *end % block_map.kernel_dims[side]);
RUY_DCHECK_LE(*end, block_map.dims[side]);
RUY_DCHECK_LT(*start, *end);
RUY_DCHECK_GE(*start, 0);
}
void GetBlockMatrixCoords(const BlockMap& block_map, const SidePair<int>& block,
SidePair<int>* start, SidePair<int>* end) {
for (Side side : {Side::kLhs, Side::kRhs}) {
GetBlockMatrixCoords(side, block_map, block, &(*start)[side],
&(*end)[side]);
}
}
} // namespace ruy
<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------//
/*!
* \file tstSamplingTools.cpp
* \author Stuart R. Slattery
* \brief Boost random number generator unit tests.
*/
//---------------------------------------------------------------------------//
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <algorithm>
#include <cassert>
#include <Chimera_RNGTraits.hpp>
#include <Chimera_BoostRNG.hpp>
#include <Chimera_SamplingTools.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_Tuple.hpp>
#include <Tpetra_Vector.hpp>
//---------------------------------------------------------------------------//
// Tests
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, uniform_stratify_sample_test )
{
using namespace Chimera;
// Setup parallel distribution.
Teuchos::RCP<const Teuchos::Comm<int> > comm =
Teuchos::DefaultComm<int>::getComm();
int comm_size = comm->getSize();
// Setup linear operator distribution.
int local_num_rows = 10;
int global_num_rows = local_num_rows*comm_size;
Teuchos::RCP<const Tpetra::Map<int> > row_map =
Tpetra::createUniformContigMap<int,int>( global_num_rows, comm );
// Build the PDF in parallel.
double pdf_val = 1.0;
Teuchos::RCP<Tpetra::Vector<double,int> > pdf =
Tpetra::createVector<double,int>( row_map );
pdf->putScalar( pdf_val );
// Stratify sample the PDF.
int num_histories = global_num_rows;
Teuchos::ArrayRCP<int> histories_per_local_state =
SamplingTools::stratifySampleGlobalPDF( num_histories, pdf );
// Check the sampling.
TEST_ASSERT( histories_per_local_state.size() == local_num_rows );
Teuchos::ArrayRCP<int>::const_iterator history_it;
for ( history_it = histories_per_local_state.begin();
history_it != histories_per_local_state.end();
++history_it )
{
TEST_ASSERT( *history_it == 1 );
}
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, nonuniform_stratify_sample_test )
{
using namespace Chimera;
// Setup parallel distribution.
Teuchos::RCP<const Teuchos::Comm<int> > comm =
Teuchos::DefaultComm<int>::getComm();
int comm_rank = comm->getRank();
int comm_size = comm->getSize();
// Setup linear operator distribution.
int local_num_rows = 10;
int global_num_rows = local_num_rows*comm_size;
Teuchos::RCP<const Tpetra::Map<int> > row_map =
Tpetra::createUniformContigMap<int,int>( global_num_rows, comm );
// Build the PDF in parallel.
double pdf_val = comm_rank + 1.0;
Teuchos::RCP<Tpetra::Vector<double,int> > pdf =
Tpetra::createVector<double,int>( row_map );
pdf->putScalar( pdf_val );
// Stratify sample the PDF.
int num_histories = 0;
for ( int i = 0; i < comm_size; ++i )
{
num_histories += local_num_rows*(i+1);
}
Teuchos::ArrayRCP<int> histories_per_local_state =
SamplingTools::stratifySampleGlobalPDF( num_histories, pdf );
// Check the sampling.
TEST_ASSERT( histories_per_local_state.size() == local_num_rows );
Teuchos::ArrayRCP<int>::const_iterator history_it;
for ( history_it = histories_per_local_state.begin();
history_it != histories_per_local_state.end();
++history_it )
{
TEST_ASSERT( *history_it == pdf_val );
}
}
//---------------------------------------------------------------------------//
// end tstBoostRNG.cpp
//---------------------------------------------------------------------------//
<commit_msg>adding local pdf sampling test. not finished yet<commit_after>//---------------------------------------------------------------------------//
/*!
* \file tstSamplingTools.cpp
* \author Stuart R. Slattery
* \brief Boost random number generator unit tests.
*/
//---------------------------------------------------------------------------//
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <algorithm>
#include <cassert>
#include <Chimera_RNGTraits.hpp>
#include <Chimera_BoostRNG.hpp>
#include <Chimera_SamplingTools.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_DefaultComm.hpp>
#include <Teuchos_CommHelpers.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_ArrayRCP.hpp>
#include <Teuchos_Array.hpp>
#include <Teuchos_OpaqueWrapper.hpp>
#include <Teuchos_TypeTraits.hpp>
#include <Teuchos_Tuple.hpp>
#include <Tpetra_Vector.hpp>
//---------------------------------------------------------------------------//
// Tests
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, uniform_stratify_sample_test )
{
using namespace Chimera;
// Setup parallel distribution.
Teuchos::RCP<const Teuchos::Comm<int> > comm =
Teuchos::DefaultComm<int>::getComm();
int comm_size = comm->getSize();
// Setup linear operator distribution.
int local_num_rows = 10;
int global_num_rows = local_num_rows*comm_size;
Teuchos::RCP<const Tpetra::Map<int> > row_map =
Tpetra::createUniformContigMap<int,int>( global_num_rows, comm );
// Build the PDF in parallel.
double pdf_val = 1.0;
Teuchos::RCP<Tpetra::Vector<double,int> > pdf =
Tpetra::createVector<double,int>( row_map );
pdf->putScalar( pdf_val );
// Stratify sample the PDF.
int num_histories = global_num_rows;
Teuchos::ArrayRCP<int> histories_per_local_state =
SamplingTools::stratifySampleGlobalPDF( num_histories, pdf );
// Check the sampling.
TEST_ASSERT( histories_per_local_state.size() == local_num_rows );
Teuchos::ArrayRCP<int>::const_iterator history_it;
for ( history_it = histories_per_local_state.begin();
history_it != histories_per_local_state.end();
++history_it )
{
TEST_ASSERT( *history_it == 1 );
}
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, nonuniform_stratify_sample_test )
{
using namespace Chimera;
// Setup parallel distribution.
Teuchos::RCP<const Teuchos::Comm<int> > comm =
Teuchos::DefaultComm<int>::getComm();
int comm_rank = comm->getRank();
int comm_size = comm->getSize();
// Setup linear operator distribution.
int local_num_rows = 10;
int global_num_rows = local_num_rows*comm_size;
Teuchos::RCP<const Tpetra::Map<int> > row_map =
Tpetra::createUniformContigMap<int,int>( global_num_rows, comm );
// Build the PDF in parallel.
double pdf_val = comm_rank + 1.0;
Teuchos::RCP<Tpetra::Vector<double,int> > pdf =
Tpetra::createVector<double,int>( row_map );
pdf->putScalar( pdf_val );
// Stratify sample the PDF.
int num_histories = 0;
for ( int i = 0; i < comm_size; ++i )
{
num_histories += local_num_rows*(i+1);
}
Teuchos::ArrayRCP<int> histories_per_local_state =
SamplingTools::stratifySampleGlobalPDF( num_histories, pdf );
// Check the sampling.
TEST_ASSERT( histories_per_local_state.size() == local_num_rows );
Teuchos::ArrayRCP<int>::const_iterator history_it;
for ( history_it = histories_per_local_state.begin();
history_it != histories_per_local_state.end();
++history_it )
{
TEST_ASSERT( *history_it == pdf_val );
}
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( SamplingTools, uniform_local_pdf_sample_test )
{
}
//---------------------------------------------------------------------------//
// end tstBoostRNG.cpp
//---------------------------------------------------------------------------//
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2012 The WebM project authors. All Rights Reserved.
Use of this source code is governed by a BSD-style license
that can be found in the LICENSE file in the root of the source
tree. An additional intellectual property rights grant can be found
in the file PATENTS. All contributing project authors may
be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <cstdlib>
#include <string>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
#include "test/md5_helper.h"
extern "C" {
#include "vpx_mem/vpx_mem.h"
}
namespace {
class TileIndependenceTest : public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWithParam<int> {
protected:
TileIndependenceTest() : EncoderTest(GET_PARAM(0)), n_tiles_(GET_PARAM(1)),
md5_fw_order_(), md5_inv_order_() {
init_flags_ = VPX_CODEC_USE_PSNR;
vpx_codec_dec_cfg_t cfg;
cfg.w = 704;
cfg.h = 144;
cfg.threads = 1;
fw_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
}
virtual ~TileIndependenceTest() {
delete fw_dec_;
delete inv_dec_;
}
virtual void SetUp() {
InitializeConfig();
SetMode(libvpx_test::kTwoPassGood);
}
virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_TILE_COLUMNS, n_tiles_);
}
}
void UpdateMD5(::libvpx_test::Decoder *dec, const vpx_codec_cx_pkt_t *pkt,
::libvpx_test::MD5 *md5) {
dec->DecodeFrame((uint8_t *) pkt->data.frame.buf, pkt->data.frame.sz);
const vpx_image_t *img = dec->GetDxData().Next();
md5->Add(img);
}
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
UpdateMD5(fw_dec_, pkt, &md5_fw_order_);
UpdateMD5(inv_dec_, pkt, &md5_inv_order_);
}
private:
int n_tiles_;
protected:
::libvpx_test::MD5 md5_fw_order_, md5_inv_order_;
::libvpx_test::Decoder *fw_dec_, *inv_dec_;
};
// run an encode with 2 or 4 tiles, and do the decode both in normal and
// inverted tile ordering. Ensure that the MD5 of the output in both cases
// is identical. If so, tiles are considered independent and the test passes.
TEST_P(TileIndependenceTest, MD5Match) {
const vpx_rational timebase = { 33333333, 1000000000 };
cfg_.g_timebase = timebase;
cfg_.rc_target_bitrate = 500;
cfg_.g_lag_in_frames = 25;
cfg_.rc_end_usage = VPX_VBR;
libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 704, 144,
timebase.den, timebase.num, 0, 30);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const char *md5_fw_str = md5_fw_order_.Get();
const char *md5_inv_str = md5_inv_order_.Get();
// could use ASSERT_EQ(!memcmp(.., .., 16) here, but this gives nicer
// output if it fails. Not sure if it's helpful since it's really just
// a MD5...
ASSERT_STREQ(md5_fw_str, md5_inv_str);
}
VP9_INSTANTIATE_TEST_CASE(TileIndependenceTest,
::testing::Range(0, 2, 1));
} // namespace
<commit_msg>test/tile_independence_test: check decode return<commit_after>/*
Copyright (c) 2012 The WebM project authors. All Rights Reserved.
Use of this source code is governed by a BSD-style license
that can be found in the LICENSE file in the root of the source
tree. An additional intellectual property rights grant can be found
in the file PATENTS. All contributing project authors may
be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <cstdlib>
#include <string>
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"
#include "test/md5_helper.h"
extern "C" {
#include "vpx_mem/vpx_mem.h"
}
namespace {
class TileIndependenceTest : public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWithParam<int> {
protected:
TileIndependenceTest() : EncoderTest(GET_PARAM(0)), n_tiles_(GET_PARAM(1)),
md5_fw_order_(), md5_inv_order_() {
init_flags_ = VPX_CODEC_USE_PSNR;
vpx_codec_dec_cfg_t cfg;
cfg.w = 704;
cfg.h = 144;
cfg.threads = 1;
fw_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_ = codec_->CreateDecoder(cfg, 0);
inv_dec_->Control(VP9_INVERT_TILE_DECODE_ORDER, 1);
}
virtual ~TileIndependenceTest() {
delete fw_dec_;
delete inv_dec_;
}
virtual void SetUp() {
InitializeConfig();
SetMode(libvpx_test::kTwoPassGood);
}
virtual void PreEncodeFrameHook(libvpx_test::VideoSource *video,
libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_TILE_COLUMNS, n_tiles_);
}
}
void UpdateMD5(::libvpx_test::Decoder *dec, const vpx_codec_cx_pkt_t *pkt,
::libvpx_test::MD5 *md5) {
const vpx_codec_err_t res =
dec->DecodeFrame(reinterpret_cast<uint8_t*>(pkt->data.frame.buf),
pkt->data.frame.sz);
if (res != VPX_CODEC_OK) {
abort_ = true;
ASSERT_EQ(VPX_CODEC_OK, res);
}
const vpx_image_t *img = dec->GetDxData().Next();
md5->Add(img);
}
virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) {
UpdateMD5(fw_dec_, pkt, &md5_fw_order_);
UpdateMD5(inv_dec_, pkt, &md5_inv_order_);
}
private:
int n_tiles_;
protected:
::libvpx_test::MD5 md5_fw_order_, md5_inv_order_;
::libvpx_test::Decoder *fw_dec_, *inv_dec_;
};
// run an encode with 2 or 4 tiles, and do the decode both in normal and
// inverted tile ordering. Ensure that the MD5 of the output in both cases
// is identical. If so, tiles are considered independent and the test passes.
TEST_P(TileIndependenceTest, MD5Match) {
const vpx_rational timebase = { 33333333, 1000000000 };
cfg_.g_timebase = timebase;
cfg_.rc_target_bitrate = 500;
cfg_.g_lag_in_frames = 25;
cfg_.rc_end_usage = VPX_VBR;
libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 704, 144,
timebase.den, timebase.num, 0, 30);
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
const char *md5_fw_str = md5_fw_order_.Get();
const char *md5_inv_str = md5_inv_order_.Get();
// could use ASSERT_EQ(!memcmp(.., .., 16) here, but this gives nicer
// output if it fails. Not sure if it's helpful since it's really just
// a MD5...
ASSERT_STREQ(md5_fw_str, md5_inv_str);
}
VP9_INSTANTIATE_TEST_CASE(TileIndependenceTest,
::testing::Range(0, 2, 1));
} // namespace
<|endoftext|>
|
<commit_before>// RUN: %clang_tsan %s -pie -fPIE -o %t && %run setarch x86_64 -R %t
int main() {
return 0;
}
<commit_msg>tsan: fix pie_no_aslr test<commit_after>// RUN: %clang_tsan %s -pie -fPIE -o %t && %run setarch x86_64 -R %t
// REQUIRES: x86_64-target-arch
int main() {
return 0;
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <ros/console.h>
#include <math.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Int8.h>
#include <std_msgs/UInt16MultiArray.h>
#include <std_msgs/Int32MultiArray.h>
// Customized message
#include <drv_msgs/target_info.h>
#include <stdio.h>
#include "targetselecter.h"
#include "facelistener.h"
#include "targetlistener.h"
using namespace std;
using namespace std_msgs;
/* Global params */
// Feedback
// 0:not working, 1:working, 2:failed, 3:finished with success
string param_vision_feedback = "/comm/param/feedback/vision/overall";
// 0:wandering, 1:searching, 2:tracking
string param_vision_feedback_mode = "/comm/param/feedback/vision/mode";
// 0:no search, 1:found, -1:current not found. -2:around not found
string param_vision_feedback_search = "/comm/param/feedback/vision/search";
// 0:no track, 1:tracking, -1:lost
string param_vision_feedback_track = "/comm/param/feedback/vision/track";
// 0:no grasp, 1:found location, -1:can't find location
string param_vision_feedback_grasp = "/comm/param/feedback/vision/grasp";
// 0:no face recognize, 1:found faces, -1:failed to recognize
string param_vision_feedback_face = "/comm/param/feedback/vision/face";
// vision shared
// true:switch on to execute tasks, false:switch off and run in wander mode
string param_vision_shared_switch = "/comm/param/shared/vision/switch";
bool centralSwitch_ = true; // main switch
// Target properties
bool targetSetTemp_ = false;
string param_target_label = "/vision/target/label";
enum TargetType{t_null, t_onTable, t_onGround, t_onHead, t_onHand};
string targetTypeName[5] = {"in air", "on the table", "on the ground",
"on the face", "in the hand"};
int tgtType_ = t_null;
string param_target_type = "/status/target/type";
string param_comm_target_set = "/comm/param/control/target/is_set";
string param_comm_target_label = "/comm/param/control/target/label";
// Target status control
string targetLabel_ = "";
bool isTargetSet_ = false;
// Target status feedback
bool foundTarget_ = false;
// Publish servo initial position
ros::Publisher servoPub_;
bool servo_initialized_ = false;
// Servo initial angles
int pitchAngle_ = 70;
int yawAngle_ = 90;
// Range of servo angles
int pitch_min_ = 60;
int pitch_max_ = 140;
int yaw_min_ = 0;
int yaw_max_ = 180;
// The rosparam that store pitch and yaw values
string param_servo_pitch = "/status/servo/pitch";
string param_servo_yaw = "/status/servo/yaw";
// Mode control params
enum ModeType{m_wander, m_search, m_track};
int modeType_ = m_wander;
int modeTypeTemp_ = -1;
string modeName[3] = {"wandering", "searching", "tracking"};
string param_running_mode = "/status/running_mode";
ros::Publisher drvPubMode_; // vision system mode publisher
// General infomation publisher
ros::Publisher drvPubInfo_;
void resetStatus()
{
// Reset global params
ros::param::set(param_vision_feedback, 0);
ros::param::set(param_vision_feedback_search, 0);
ros::param::set(param_vision_feedback_track, 0);
ros::param::set(param_vision_feedback_grasp, 0);
ros::param::set(param_vision_feedback_face, 0);
tgtType_ = t_null;
targetLabel_ = "";
isTargetSet_ = false;
foundTarget_ = false;
modeType_ = m_wander;
ros::param::set(param_comm_target_set, false);
ros::param::set(param_comm_target_label, "");
}
/* This function is used for servo initialization and
* publishing servo angles received from cellphone
*/
void pubServo(int pitch_angle, int yaw_angle, int power)
{
std_msgs::UInt16MultiArray array;
array.data.push_back(pitch_angle);
array.data.push_back(yaw_angle);
array.data.push_back(50 * power);
servoPub_.publish(array);
}
void pubInfo(string info)
{
ROS_INFO(info.c_str());
String msg;
msg.data = info;
drvPubInfo_.publish(msg);
}
void teleOpCallback(const Int32MultiArrayConstPtr &msg)
{
if (msg->data.empty() || (msg->data[0] == 0 && msg->data[1] == 0))
return;
int pitch_temp = pitchAngle_ + msg->data[0];
if (pitch_temp < pitch_min_ || pitch_temp > pitch_max_)
return;
else
pitchAngle_ = pitch_temp;
int yaw_temp = yawAngle_ - msg->data[1];
if (yaw_temp < yaw_min_ || yaw_temp > yaw_max_)
return;
else
yawAngle_ = yaw_temp;
int power = 2;
pubServo(pitchAngle_, yawAngle_, power);
}
void servoCallback(const UInt16MultiArrayConstPtr &msg)
{
// This callback should always active
pitchAngle_ = msg->data[0];
yawAngle_ = msg->data[1];
ros::param::set(param_servo_pitch, pitchAngle_);
ros::param::set(param_servo_yaw, yawAngle_);
}
void searchCallback(const Int8ConstPtr &msg)
{
if (modeType_ == m_search) {
if (msg->data == -1) {
pubInfo("Search around didn't get target, continue searching...");
foundTarget_ = false;
ros::param::set(param_vision_feedback_search, -2);
ros::param::set(param_vision_feedback, 2);
}
else if (msg->data == 0) {
pubInfo("Currently didn't find target, continue searching...");
ros::param::set(param_vision_feedback_search, -1);
ros::param::set(param_vision_feedback, 1);
foundTarget_ = false;
}
else {
foundTarget_ = true;
ros::param::set(param_vision_feedback_search, 1);
ros::param::set(param_vision_feedback, 1);
}
}
}
void trackCallback(const BoolConstPtr &msg)
{
if (modeType_ == m_track) {
if (!msg->data) {
ROS_INFO("Track report: Target lost!");
foundTarget_ = false;
ros::param::set(param_vision_feedback_track, -1);
ros::param::set(param_vision_feedback, 1);
}
else {
ROS_INFO_THROTTLE(7, "Track report: Tracking...");
foundTarget_ = true;
ros::param::set(param_vision_feedback_track, 1);
ros::param::set(param_vision_feedback, 1);
}
}
}
void graspCallback(const Int8ConstPtr &msg)
{
if (modeType_ == m_track) {
if (!msg->data) {
ROS_INFO_THROTTLE(3, "Grasp report: Failed.");
ros::param::set(param_vision_feedback_grasp, -1);
ros::param::set(param_vision_feedback, 1);
}
else if (msg->data == 1) {
ROS_INFO_THROTTLE(3, "Grasp report: Reaching to the target...");
ros::param::set(param_vision_feedback_grasp, 1);
ros::param::set(param_vision_feedback, 1);
}
else {
ROS_INFO("Grasp report: Target in reach.");
// Reset if grasping has been performed
resetStatus();
}
}
}
void faceRecognizeCallback(const BoolConstPtr &msg)
{
if (modeType_ == m_wander) {
if (!msg->data) {
pubInfo("Face report: Failed.");
ros::param::set(param_vision_feedback_face, -1);
ros::param::set(param_vision_feedback, 2);
}
else {
pubInfo("Face report: Successed.");
ros::param::set(param_vision_feedback_face, 1);
ros::param::set(param_vision_feedback, 3);
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "drv_brain");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
pnh.getParam("pitch_min", pitch_min_);
pnh.getParam("pitch_max", pitch_max_);
pnh.getParam("yaw_min", yaw_min_);
pnh.getParam("yaw_max", yaw_max_);
servoPub_ = nh.advertise<UInt16MultiArray>("servo", 1, true);
// For publishing mode info
drvPubMode_ = nh.advertise<String>("/comm/msg/vision/mode", 1);
drvPubInfo_ = nh.advertise<String>("/comm/msg/vision/info", 1);
// Don't change the order without reason
ros::Subscriber sub_servo_ctrl = nh.subscribe<Int32MultiArray>("/joy_teleop/servo", 1, teleOpCallback);
ros::Subscriber sub_servo = nh.subscribe<UInt16MultiArray>("servo", 1, servoCallback);
//ros::Subscriber sub_tgt = nh.subscribe<drv_msgs::target_info>("recognize/target", 1, targetCallback);
ros::Subscriber sub_sh = nh.subscribe<Int8>("status/search/feedback", 1, searchCallback);
ros::Subscriber sub_tk = nh.subscribe<Bool>("status/track/feedback", 1, trackCallback);
ros::Subscriber sub_gp = nh.subscribe<Int8>("status/grasp/feedback", 1, graspCallback);
ros::Subscriber sub_fr = nh.subscribe<Bool>("status/face/feedback", 1, faceRecognizeCallback);
FaceListener fl;
TargetListener tl;
TargetSelecter ts;
resetStatus();
pubInfo("Deep Robot Vision system initialized!");
while (ros::ok()) {
// Main on/off control
if (ros::param::has(param_vision_shared_switch)) {
bool temp = true;
ros::param::get(param_vision_shared_switch, temp);
if (temp)
ROS_WARN_COND(!centralSwitch_, "Central switch is ON.");
centralSwitch_ = temp;
}
if (!centralSwitch_) {
ROS_WARN_THROTTLE(9, "Central switch is OFF.");
resetStatus();
continue;
}
// Initialize servo position
if (!servo_initialized_) {
pubServo(90, 90, 1);
servo_initialized_ = true;
ROS_INFO("Servo reset.");
}
// Get feedback to determine whether target were found
ros::spinOnce();
// Get target label if the params were set
tl.getTargetStatus(isTargetSet_, targetLabel_);
ros::param::set(param_target_label, targetLabel_);
if (isTargetSet_ != targetSetTemp_) {
if (isTargetSet_)
pubInfo("Target set to be '" + targetLabel_ + "'.");
else {
pubInfo("Target cancelled.");
resetStatus();
}
targetSetTemp_ = isTargetSet_;
}
// If user selects target on cellphone, publish the target
ts.publishOnceIfTargetSelected(isTargetSet_, foundTarget_);
// Mode selection, notice that modeType_ should only be set by central control
if (isTargetSet_) {
if (foundTarget_) {
// No matter whether the target is searched or selected by user,
// as long as it was found, track it.
modeType_ = m_track;
}
else {
if (targetLabel_ == "user selected object") {
// If the target is selected by user but no more been found,
// which means tracking has lost it, reset.
pubInfo("Tracking did not follow.");
resetStatus();
}
else
modeType_ = m_search;
}
}
else {
modeType_ = m_wander;
fl.isNeedRecognizeFace(); // Only recognize face in wander mode
}
// Set running mode
ros::param::set(param_running_mode, modeType_);
if (modeType_ != modeTypeTemp_) {
String mode_msg;
mode_msg.data = modeName[modeType_];
drvPubMode_.publish(mode_msg);
ROS_INFO("Current mode: %s.", modeName[modeType_].c_str());
modeTypeTemp_ = modeType_;
if (modeType_ == m_wander) {
// Reset head pose
servo_initialized_ = false;
}
}
}
return 0;
}
<commit_msg>adjust speed<commit_after>#include <ros/ros.h>
#include <ros/console.h>
#include <math.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/CameraInfo.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Int8.h>
#include <std_msgs/UInt16MultiArray.h>
#include <std_msgs/Int32MultiArray.h>
// Customized message
#include <drv_msgs/target_info.h>
#include <stdio.h>
#include "targetselecter.h"
#include "facelistener.h"
#include "targetlistener.h"
using namespace std;
using namespace std_msgs;
/* Global params */
// Feedback
// 0:not working, 1:working, 2:failed, 3:finished with success
string param_vision_feedback = "/comm/param/feedback/vision/overall";
// 0:wandering, 1:searching, 2:tracking
string param_vision_feedback_mode = "/comm/param/feedback/vision/mode";
// 0:no search, 1:found, -1:current not found. -2:around not found
string param_vision_feedback_search = "/comm/param/feedback/vision/search";
// 0:no track, 1:tracking, -1:lost
string param_vision_feedback_track = "/comm/param/feedback/vision/track";
// 0:no grasp, 1:found location, -1:can't find location
string param_vision_feedback_grasp = "/comm/param/feedback/vision/grasp";
// 0:no face recognize, 1:found faces, -1:failed to recognize
string param_vision_feedback_face = "/comm/param/feedback/vision/face";
// vision shared
// true:switch on to execute tasks, false:switch off and run in wander mode
string param_vision_shared_switch = "/comm/param/shared/vision/switch";
bool centralSwitch_ = true; // main switch
// Target properties
bool targetSetTemp_ = false;
string param_target_label = "/vision/target/label";
enum TargetType{t_null, t_onTable, t_onGround, t_onHead, t_onHand};
string targetTypeName[5] = {"in air", "on the table", "on the ground",
"on the face", "in the hand"};
int tgtType_ = t_null;
string param_target_type = "/status/target/type";
string param_comm_target_set = "/comm/param/control/target/is_set";
string param_comm_target_label = "/comm/param/control/target/label";
// Target status control
string targetLabel_ = "";
bool isTargetSet_ = false;
// Target status feedback
bool foundTarget_ = false;
// Publish servo initial position
ros::Publisher servoPub_;
bool servo_initialized_ = false;
// Servo initial angles
int pitchAngle_ = 70;
int yawAngle_ = 90;
// Range of servo angles
int pitch_min_ = 60;
int pitch_max_ = 140;
int yaw_min_ = 0;
int yaw_max_ = 180;
// The rosparam that store pitch and yaw values
string param_servo_pitch = "/status/servo/pitch";
string param_servo_yaw = "/status/servo/yaw";
// Mode control params
enum ModeType{m_wander, m_search, m_track};
int modeType_ = m_wander;
int modeTypeTemp_ = -1;
string modeName[3] = {"wandering", "searching", "tracking"};
string param_running_mode = "/status/running_mode";
ros::Publisher drvPubMode_; // vision system mode publisher
// General infomation publisher
ros::Publisher drvPubInfo_;
void resetStatus()
{
// Reset global params
ros::param::set(param_vision_feedback, 0);
ros::param::set(param_vision_feedback_search, 0);
ros::param::set(param_vision_feedback_track, 0);
ros::param::set(param_vision_feedback_grasp, 0);
ros::param::set(param_vision_feedback_face, 0);
tgtType_ = t_null;
targetLabel_ = "";
isTargetSet_ = false;
foundTarget_ = false;
modeType_ = m_wander;
ros::param::set(param_comm_target_set, false);
ros::param::set(param_comm_target_label, "");
}
/* This function is used for servo initialization and
* publishing servo angles received from cellphone
*/
void pubServo(int pitch_angle, int yaw_angle, int power)
{
std_msgs::UInt16MultiArray array;
array.data.push_back(pitch_angle);
array.data.push_back(yaw_angle);
array.data.push_back(20 * power);
servoPub_.publish(array);
}
void pubInfo(string info)
{
ROS_INFO(info.c_str());
String msg;
msg.data = info;
drvPubInfo_.publish(msg);
}
void teleOpCallback(const Int32MultiArrayConstPtr &msg)
{
if (msg->data.empty() || (msg->data[0] == 0 && msg->data[1] == 0))
return;
int pitch_temp = pitchAngle_ + msg->data[0];
if (pitch_temp < pitch_min_ || pitch_temp > pitch_max_)
return;
else
pitchAngle_ = pitch_temp;
int yaw_temp = yawAngle_ - msg->data[1];
if (yaw_temp < yaw_min_ || yaw_temp > yaw_max_)
return;
else
yawAngle_ = yaw_temp;
int power = 2;
pubServo(pitchAngle_, yawAngle_, power);
}
void servoCallback(const UInt16MultiArrayConstPtr &msg)
{
// This callback should always active
pitchAngle_ = msg->data[0];
yawAngle_ = msg->data[1];
ros::param::set(param_servo_pitch, pitchAngle_);
ros::param::set(param_servo_yaw, yawAngle_);
}
void searchCallback(const Int8ConstPtr &msg)
{
if (modeType_ == m_search) {
if (msg->data == -1) {
pubInfo("Search around didn't get target, continue searching...");
foundTarget_ = false;
ros::param::set(param_vision_feedback_search, -2);
ros::param::set(param_vision_feedback, 2);
}
else if (msg->data == 0) {
pubInfo("Currently didn't find target, continue searching...");
ros::param::set(param_vision_feedback_search, -1);
ros::param::set(param_vision_feedback, 1);
foundTarget_ = false;
}
else {
foundTarget_ = true;
ros::param::set(param_vision_feedback_search, 1);
ros::param::set(param_vision_feedback, 1);
}
}
}
void trackCallback(const BoolConstPtr &msg)
{
if (modeType_ == m_track) {
if (!msg->data) {
ROS_INFO("Track report: Target lost!");
foundTarget_ = false;
ros::param::set(param_vision_feedback_track, -1);
ros::param::set(param_vision_feedback, 1);
}
else {
ROS_INFO_THROTTLE(7, "Track report: Tracking...");
foundTarget_ = true;
ros::param::set(param_vision_feedback_track, 1);
ros::param::set(param_vision_feedback, 1);
}
}
}
void graspCallback(const Int8ConstPtr &msg)
{
if (modeType_ == m_track) {
if (!msg->data) {
ROS_INFO_THROTTLE(3, "Grasp report: Failed.");
ros::param::set(param_vision_feedback_grasp, -1);
ros::param::set(param_vision_feedback, 1);
}
else if (msg->data == 1) {
ROS_INFO_THROTTLE(3, "Grasp report: Reaching to the target...");
ros::param::set(param_vision_feedback_grasp, 1);
ros::param::set(param_vision_feedback, 1);
}
else {
ROS_INFO("Grasp report: Target in reach.");
// Reset if grasping has been performed
resetStatus();
}
}
}
void faceRecognizeCallback(const BoolConstPtr &msg)
{
if (modeType_ == m_wander) {
if (!msg->data) {
pubInfo("Face report: Failed.");
ros::param::set(param_vision_feedback_face, -1);
ros::param::set(param_vision_feedback, 2);
}
else {
pubInfo("Face report: Successed.");
ros::param::set(param_vision_feedback_face, 1);
ros::param::set(param_vision_feedback, 3);
}
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "drv_brain");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
pnh.getParam("pitch_min", pitch_min_);
pnh.getParam("pitch_max", pitch_max_);
pnh.getParam("yaw_min", yaw_min_);
pnh.getParam("yaw_max", yaw_max_);
servoPub_ = nh.advertise<UInt16MultiArray>("servo", 1, true);
// For publishing mode info
drvPubMode_ = nh.advertise<String>("/comm/msg/vision/mode", 1);
drvPubInfo_ = nh.advertise<String>("/comm/msg/vision/info", 1);
// Don't change the order without reason
ros::Subscriber sub_servo_ctrl = nh.subscribe<Int32MultiArray>("/joy_teleop/servo", 1, teleOpCallback);
ros::Subscriber sub_servo = nh.subscribe<UInt16MultiArray>("servo", 1, servoCallback);
//ros::Subscriber sub_tgt = nh.subscribe<drv_msgs::target_info>("recognize/target", 1, targetCallback);
ros::Subscriber sub_sh = nh.subscribe<Int8>("status/search/feedback", 1, searchCallback);
ros::Subscriber sub_tk = nh.subscribe<Bool>("status/track/feedback", 1, trackCallback);
ros::Subscriber sub_gp = nh.subscribe<Int8>("status/grasp/feedback", 1, graspCallback);
ros::Subscriber sub_fr = nh.subscribe<Bool>("status/face/feedback", 1, faceRecognizeCallback);
FaceListener fl;
TargetListener tl;
TargetSelecter ts;
resetStatus();
pubInfo("Deep Robot Vision system initialized!");
while (ros::ok()) {
// Main on/off control
if (ros::param::has(param_vision_shared_switch)) {
bool temp = true;
ros::param::get(param_vision_shared_switch, temp);
if (temp)
ROS_WARN_COND(!centralSwitch_, "Central switch is ON.");
centralSwitch_ = temp;
}
if (!centralSwitch_) {
ROS_WARN_THROTTLE(9, "Central switch is OFF.");
resetStatus();
continue;
}
// Initialize servo position
if (!servo_initialized_) {
pubServo(90, 90, 1);
servo_initialized_ = true;
ROS_INFO("Servo reset.");
}
// Get feedback to determine whether target were found
ros::spinOnce();
// Get target label if the params were set
tl.getTargetStatus(isTargetSet_, targetLabel_);
ros::param::set(param_target_label, targetLabel_);
if (isTargetSet_ != targetSetTemp_) {
if (isTargetSet_)
pubInfo("Target set to be '" + targetLabel_ + "'.");
else {
pubInfo("Target cancelled.");
resetStatus();
}
targetSetTemp_ = isTargetSet_;
}
// If user selects target on cellphone, publish the target
ts.publishOnceIfTargetSelected(isTargetSet_, foundTarget_);
// Mode selection, notice that modeType_ should only be set by central control
if (isTargetSet_) {
if (foundTarget_) {
// No matter whether the target is searched or selected by user,
// as long as it was found, track it.
modeType_ = m_track;
}
else {
if (targetLabel_ == "user selected object") {
// If the target is selected by user but no more been found,
// which means tracking has lost it, reset.
pubInfo("Tracking did not follow.");
resetStatus();
}
else
modeType_ = m_search;
}
}
else {
modeType_ = m_wander;
fl.isNeedRecognizeFace(); // Only recognize face in wander mode
}
// Set running mode
ros::param::set(param_running_mode, modeType_);
if (modeType_ != modeTypeTemp_) {
String mode_msg;
mode_msg.data = modeName[modeType_];
drvPubMode_.publish(mode_msg);
ROS_INFO("Current mode: %s.", modeName[modeType_].c_str());
modeTypeTemp_ = modeType_;
if (modeType_ == m_wander) {
// Reset head pose
servo_initialized_ = false;
}
}
}
return 0;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.