<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: itemiter.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 21:44:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#ifndef GCC
#endif

#include <svtools/itemiter.hxx>
#include <svtools/itempool.hxx>
#include <svtools/itemset.hxx>

// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxItemIter);

// --------------------------------------------------------------------------

SfxItemIter::SfxItemIter( const SfxItemSet& rItemSet )
    : _rSet( rItemSet )
{
    DBG_CTOR(SfxItemIter, 0);
    DBG_ASSERTWARNING( _rSet.Count(), "es gibt gar keine Attribute" );

    if ( !_rSet._nCount )
    {
        _nStt = 1;
        _nEnd = 0;
    }
    else
    {
        SfxItemArray ppFnd = _rSet._aItems;

        // suche das 1. gesetzte Item
        for ( _nStt = 0; !*(ppFnd + _nStt ); ++_nStt )
            ; // empty loop
        if ( 1 < _rSet.Count() )
            for( _nEnd = _rSet.TotalCount(); !*( ppFnd + --_nEnd);  )
                ; // empty loop
        else
            _nEnd = _nStt;
    }

    _nAkt = _nStt;
}

// --------------------------------------------------------------------------

SfxItemIter::~SfxItemIter()
{
    DBG_DTOR(SfxItemIter, 0);
}

// --------------------------------------------------------------------------

const SfxPoolItem* SfxItemIter::NextItem()
{
    DBG_CHKTHIS(SfxItemIter, 0);
    SfxItemArray ppFnd = _rSet._aItems;

    if( _nAkt < _nEnd )
    {
        do {
            _nAkt++;
        } while( _nAkt < _nEnd && !*(ppFnd + _nAkt ) );
        return *(ppFnd+_nAkt);
    }
    return 0;
}

// --------------------------------------------------------------------------

const SfxPoolItem* SfxItemIter::PrevItem()
{
    DBG_CHKTHIS(SfxItemIter, 0);
    SfxItemArray ppFnd = _rSet._aItems;

    if ( _nAkt > _nStt )
    {
        do {
            --_nAkt;
        } while( _nAkt && !*(ppFnd + _nAkt ));
        return *(ppFnd+_nAkt);
    }
    return 0;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.5.246); FILE MERGED 2008/03/31 13:02:10 rt 1.5.246.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: itemiter.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#ifndef GCC
#endif

#include <svtools/itemiter.hxx>
#include <svtools/itempool.hxx>
#include <svtools/itemset.hxx>

// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxItemIter);

// --------------------------------------------------------------------------

SfxItemIter::SfxItemIter( const SfxItemSet& rItemSet )
    : _rSet( rItemSet )
{
    DBG_CTOR(SfxItemIter, 0);
    DBG_ASSERTWARNING( _rSet.Count(), "es gibt gar keine Attribute" );

    if ( !_rSet._nCount )
    {
        _nStt = 1;
        _nEnd = 0;
    }
    else
    {
        SfxItemArray ppFnd = _rSet._aItems;

        // suche das 1. gesetzte Item
        for ( _nStt = 0; !*(ppFnd + _nStt ); ++_nStt )
            ; // empty loop
        if ( 1 < _rSet.Count() )
            for( _nEnd = _rSet.TotalCount(); !*( ppFnd + --_nEnd);  )
                ; // empty loop
        else
            _nEnd = _nStt;
    }

    _nAkt = _nStt;
}

// --------------------------------------------------------------------------

SfxItemIter::~SfxItemIter()
{
    DBG_DTOR(SfxItemIter, 0);
}

// --------------------------------------------------------------------------

const SfxPoolItem* SfxItemIter::NextItem()
{
    DBG_CHKTHIS(SfxItemIter, 0);
    SfxItemArray ppFnd = _rSet._aItems;

    if( _nAkt < _nEnd )
    {
        do {
            _nAkt++;
        } while( _nAkt < _nEnd && !*(ppFnd + _nAkt ) );
        return *(ppFnd+_nAkt);
    }
    return 0;
}

// --------------------------------------------------------------------------

const SfxPoolItem* SfxItemIter::PrevItem()
{
    DBG_CHKTHIS(SfxItemIter, 0);
    SfxItemArray ppFnd = _rSet._aItems;

    if ( _nAkt > _nStt )
    {
        do {
            --_nAkt;
        } while( _nAkt && !*(ppFnd + _nAkt ));
        return *(ppFnd+_nAkt);
    }
    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ndnotxt.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 21:00:09 $
 *
 *  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"

#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif

#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _CONTDLG_HXX_
#include <svx/contdlg.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _FMTCOL_HXX
#include <fmtcol.hxx>
#endif
#ifndef _NDNOTXT_HXX
#include <ndnotxt.hxx>
#endif
#ifndef _NDGRF_HXX
#include <ndgrf.hxx>
#endif
#ifndef _NDOLE_HXX
#include <ndole.hxx>
#endif
#ifndef _NDINDEX_HXX
#include <ndindex.hxx>
#endif
#ifndef _HINTS_HXX
#include <hints.hxx>            // fuer SwFmtChg
#endif

SwNoTxtNode::SwNoTxtNode( const SwNodeIndex & rWhere,
                  const BYTE nNdType,
                  SwGrfFmtColl *pGrfColl,
                  SwAttrSet* pAutoAttr ) :
    SwCntntNode( rWhere, nNdType, pGrfColl ),
    pContour( 0 ),
    bAutomaticContour( FALSE ),
    bContourMapModeValid( TRUE ),
    bPixelContour( FALSE )
{
    // soll eine Harte-Attributierung gesetzt werden?
    if( pAutoAttr )
        SetAttr( *pAutoAttr );
}

SwNoTxtNode::~SwNoTxtNode()
{
    delete pContour;
}

// erzeugt fuer alle Ableitungen einen AttrSet mit Bereichen
// fuer Frame- und Grafik-Attributen
void SwNoTxtNode::NewAttrSet( SwAttrPool& rPool )
{
    ASSERT( !pAttrSet, "AttrSet ist doch gesetzt" );
    pAttrSet = new SwAttrSet( rPool, aNoTxtNodeSetRange );
    pAttrSet->SetParent( &GetFmtColl()->GetAttrSet() );
}

// Dummies fuer das Laden/Speichern von persistenten Daten
// bei Grafiken und OLE-Objekten

BOOL SwNoTxtNode::RestorePersistentData()
{
    return TRUE;
}

BOOL SwNoTxtNode::SavePersistentData()
{
    return TRUE;
}

void SwNoTxtNode::SetContour( const PolyPolygon *pPoly, BOOL bAutomatic )
{
    delete pContour;
    if ( pPoly )
        pContour = new PolyPolygon( *pPoly );
    else
        pContour = 0;
    bAutomaticContour = bAutomatic;
    bContourMapModeValid = TRUE;
    bPixelContour = FALSE;
}

void SwNoTxtNode::CreateContour()
{
    ASSERT( !pContour, "Contour available." );
    pContour = new PolyPolygon(SvxContourDlg::CreateAutoContour(GetGraphic()));
    bAutomaticContour = TRUE;
    bContourMapModeValid = TRUE;
    bPixelContour = FALSE;
}

const PolyPolygon *SwNoTxtNode::HasContour() const
{
    if( !bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        BOOL bPixelGrf = aGrfMap.GetMapUnit() == MAP_PIXEL;
        const MapMode aContourMap( bPixelGrf ? MAP_PIXEL : MAP_100TH_MM );
        if( bPixelGrf ? !bPixelContour : aGrfMap != aContourMap )
        {
            ASSERT( !bPixelGrf || aGrfMap == aContourMap,
                    "scale factor for pixel unsupported" );
            OutputDevice* pOutDev =
                (bPixelGrf || bPixelContour) ? Application::GetDefaultDevice()
                                             : 0;
            USHORT nPolyCount = pContour->Count();
            for( USHORT j=0; j<nPolyCount; j++ )
            {
                Polygon& rPoly = (*pContour)[j];

                USHORT nCount = rPoly.GetSize();
                for( USHORT i=0 ; i<nCount; i++ )
                {
                    if( bPixelGrf )
                        rPoly[i] = pOutDev->LogicToPixel( rPoly[i],
                                                          aContourMap );
                    else if( bPixelContour )
                        rPoly[i] = pOutDev->PixelToLogic( rPoly[i], aGrfMap );
                    else
                        rPoly[i] = OutputDevice::LogicToLogic( rPoly[i],
                                                                 aContourMap,
                                                                 aGrfMap );
                }
            }
        }
        ((SwNoTxtNode *)this)->bContourMapModeValid = TRUE;
        ((SwNoTxtNode *)this)->bPixelContour = FALSE;
    }

    return pContour;
}

void SwNoTxtNode::GetContour( PolyPolygon &rPoly ) const
{
    ASSERT( pContour, "Contour not available." );
    rPoly = *HasContour();
}

void SwNoTxtNode::SetContourAPI( const PolyPolygon *pPoly )
{
    delete pContour;
    if ( pPoly )
        pContour = new PolyPolygon( *pPoly );
    else
        pContour = 0;
    bContourMapModeValid = FALSE;
}

BOOL SwNoTxtNode::GetContourAPI( PolyPolygon &rContour ) const
{
    if( !pContour )
        return FALSE;

    rContour = *pContour;
    if( bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        const MapMode aContourMap( MAP_100TH_MM );
        ASSERT( aGrfMap.GetMapUnit() != MAP_PIXEL ||
                aGrfMap == MapMode( MAP_PIXEL ),
                    "scale factor for pixel unsupported" );
        if( aGrfMap.GetMapUnit() != MAP_PIXEL &&
            aGrfMap != aContourMap )
        {
            USHORT nPolyCount = rContour.Count();
            for( USHORT j=0; j<nPolyCount; j++ )
            {
                Polygon& rPoly = (*pContour)[j];

                USHORT nCount = rPoly.GetSize();
                for( USHORT i=0 ; i<nCount; i++ )
                {
                    rPoly[i] = OutputDevice::LogicToLogic( rPoly[i], aGrfMap,
                                                           aContourMap );
                }
            }
        }
    }

    return TRUE;
}

const BOOL SwNoTxtNode::IsPixelContour() const
{
    BOOL bRet;
    if( bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        bRet = aGrfMap.GetMapUnit() == MAP_PIXEL;
    }
    else
    {
        bRet = bPixelContour;
    }

    return bRet;
}

Graphic SwNoTxtNode::GetGraphic() const
{
    Graphic aRet;
    if ( GetGrfNode() )
    {
        ((SwGrfNode*)this)->SwapIn( TRUE );
        aRet = ((SwGrfNode*)this)->GetGrf();
    }
    else
    {
        ASSERT( GetOLENode(), "new type of Node?" );
        aRet = *((SwOLENode*)this)->SwOLENode::GetGraphic();
    }
    return aRet;
}

void SwNoTxtNode::SetAlternateText( const String& rTxt, sal_Bool bBroadcast )
{
    if( bBroadcast )
    {
        SwStringMsgPoolItem aOld( RES_ALT_TEXT_CHANGED, aAlternateText );
        SwStringMsgPoolItem aNew( RES_ALT_TEXT_CHANGED, rTxt );
        aAlternateText = rTxt;
        Modify( &aOld, &aNew );
    }
    else
    {
        aAlternateText = rTxt;
    }
}

<commit_msg>INTEGRATION: CWS swautomatic01 (1.9.326); FILE MERGED 2006/10/10 17:21:38 fme 1.9.326.5: RESYNC: (1.9-1.10); FILE MERGED 2006/08/18 09:04:02 fme 1.9.326.4: #i65476# Automatic paragraph styles 2006/08/16 09:34:05 fme 1.9.326.3: #i65476# AutoStyles for paragraphs 2006/08/09 08:56:30 fme 1.9.326.2: #i64576# Automatic styles 2006/08/01 15:00:02 fme 1.9.326.1: #i64576# Automatic styles<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ndnotxt.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2006-12-01 15:41:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif

#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#include <svtools/stritem.hxx>
#ifndef _CONTDLG_HXX_
#include <svx/contdlg.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _FMTCOL_HXX
#include <fmtcol.hxx>
#endif
#ifndef _NDNOTXT_HXX
#include <ndnotxt.hxx>
#endif
#ifndef _NDGRF_HXX
#include <ndgrf.hxx>
#endif
#ifndef _NDOLE_HXX
#include <ndole.hxx>
#endif
#ifndef _NDINDEX_HXX
#include <ndindex.hxx>
#endif
#ifndef _HINTS_HXX
#include <hints.hxx>            // fuer SwFmtChg
#endif
#include <istyleaccess.hxx>
#include <SwStyleNameMapper.hxx>

SwNoTxtNode::SwNoTxtNode( const SwNodeIndex & rWhere,
                  const BYTE nNdType,
                  SwGrfFmtColl *pGrfColl,
                  SwAttrSet* pAutoAttr ) :
    SwCntntNode( rWhere, nNdType, pGrfColl ),
    pContour( 0 ),
    bAutomaticContour( FALSE ),
    bContourMapModeValid( TRUE ),
    bPixelContour( FALSE )
{
    // soll eine Harte-Attributierung gesetzt werden?
    if( pAutoAttr )
        SetAttr( *pAutoAttr );
}

SwNoTxtNode::~SwNoTxtNode()
{
    delete pContour;
}

// erzeugt fuer alle Ableitungen einen AttrSet mit Bereichen
// fuer Frame- und Grafik-Attributen
void SwNoTxtNode::NewAttrSet( SwAttrPool& rPool )
{
    ASSERT( !mpAttrSet.get(), "AttrSet ist doch gesetzt" );
    SwAttrSet aNewAttrSet( rPool, aNoTxtNodeSetRange );

    // put names of parent style and conditional style:
    const SwFmtColl* pFmtColl = GetFmtColl();
    String sVal;
    SwStyleNameMapper::FillProgName( pFmtColl->GetName(), sVal, GET_POOLID_TXTCOLL, sal_True );
    SfxStringItem aFmtColl( RES_FRMATR_STYLE_NAME, sVal );
    aNewAttrSet.Put( aFmtColl );

    aNewAttrSet.SetParent( &GetFmtColl()->GetAttrSet() );
    mpAttrSet = GetDoc()->GetIStyleAccess().getAutomaticStyle( aNewAttrSet, IStyleAccess::AUTO_STYLE_NOTXT );
}

// Dummies fuer das Laden/Speichern von persistenten Daten
// bei Grafiken und OLE-Objekten

BOOL SwNoTxtNode::RestorePersistentData()
{
    return TRUE;
}

BOOL SwNoTxtNode::SavePersistentData()
{
    return TRUE;
}

void SwNoTxtNode::SetContour( const PolyPolygon *pPoly, BOOL bAutomatic )
{
    delete pContour;
    if ( pPoly )
        pContour = new PolyPolygon( *pPoly );
    else
        pContour = 0;
    bAutomaticContour = bAutomatic;
    bContourMapModeValid = TRUE;
    bPixelContour = FALSE;
}

void SwNoTxtNode::CreateContour()
{
    ASSERT( !pContour, "Contour available." );
    pContour = new PolyPolygon(SvxContourDlg::CreateAutoContour(GetGraphic()));
    bAutomaticContour = TRUE;
    bContourMapModeValid = TRUE;
    bPixelContour = FALSE;
}

const PolyPolygon *SwNoTxtNode::HasContour() const
{
    if( !bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        BOOL bPixelGrf = aGrfMap.GetMapUnit() == MAP_PIXEL;
        const MapMode aContourMap( bPixelGrf ? MAP_PIXEL : MAP_100TH_MM );
        if( bPixelGrf ? !bPixelContour : aGrfMap != aContourMap )
        {
            ASSERT( !bPixelGrf || aGrfMap == aContourMap,
                    "scale factor for pixel unsupported" );
            OutputDevice* pOutDev =
                (bPixelGrf || bPixelContour) ? Application::GetDefaultDevice()
                                             : 0;
            USHORT nPolyCount = pContour->Count();
            for( USHORT j=0; j<nPolyCount; j++ )
            {
                Polygon& rPoly = (*pContour)[j];

                USHORT nCount = rPoly.GetSize();
                for( USHORT i=0 ; i<nCount; i++ )
                {
                    if( bPixelGrf )
                        rPoly[i] = pOutDev->LogicToPixel( rPoly[i],
                                                          aContourMap );
                    else if( bPixelContour )
                        rPoly[i] = pOutDev->PixelToLogic( rPoly[i], aGrfMap );
                    else
                        rPoly[i] = OutputDevice::LogicToLogic( rPoly[i],
                                                                 aContourMap,
                                                                 aGrfMap );
                }
            }
        }
        ((SwNoTxtNode *)this)->bContourMapModeValid = TRUE;
        ((SwNoTxtNode *)this)->bPixelContour = FALSE;
    }

    return pContour;
}

void SwNoTxtNode::GetContour( PolyPolygon &rPoly ) const
{
    ASSERT( pContour, "Contour not available." );
    rPoly = *HasContour();
}

void SwNoTxtNode::SetContourAPI( const PolyPolygon *pPoly )
{
    delete pContour;
    if ( pPoly )
        pContour = new PolyPolygon( *pPoly );
    else
        pContour = 0;
    bContourMapModeValid = FALSE;
}

BOOL SwNoTxtNode::GetContourAPI( PolyPolygon &rContour ) const
{
    if( !pContour )
        return FALSE;

    rContour = *pContour;
    if( bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        const MapMode aContourMap( MAP_100TH_MM );
        ASSERT( aGrfMap.GetMapUnit() != MAP_PIXEL ||
                aGrfMap == MapMode( MAP_PIXEL ),
                    "scale factor for pixel unsupported" );
        if( aGrfMap.GetMapUnit() != MAP_PIXEL &&
            aGrfMap != aContourMap )
        {
            USHORT nPolyCount = rContour.Count();
            for( USHORT j=0; j<nPolyCount; j++ )
            {
                Polygon& rPoly = (*pContour)[j];

                USHORT nCount = rPoly.GetSize();
                for( USHORT i=0 ; i<nCount; i++ )
                {
                    rPoly[i] = OutputDevice::LogicToLogic( rPoly[i], aGrfMap,
                                                           aContourMap );
                }
            }
        }
    }

    return TRUE;
}

const BOOL SwNoTxtNode::IsPixelContour() const
{
    BOOL bRet;
    if( bContourMapModeValid )
    {
        const MapMode aGrfMap( GetGraphic().GetPrefMapMode() );
        bRet = aGrfMap.GetMapUnit() == MAP_PIXEL;
    }
    else
    {
        bRet = bPixelContour;
    }

    return bRet;
}

Graphic SwNoTxtNode::GetGraphic() const
{
    Graphic aRet;
    if ( GetGrfNode() )
    {
        ((SwGrfNode*)this)->SwapIn( TRUE );
        aRet = ((SwGrfNode*)this)->GetGrf();
    }
    else
    {
        ASSERT( GetOLENode(), "new type of Node?" );
        aRet = *((SwOLENode*)this)->SwOLENode::GetGraphic();
    }
    return aRet;
}

void SwNoTxtNode::SetAlternateText( const String& rTxt, sal_Bool bBroadcast )
{
    if( bBroadcast )
    {
        SwStringMsgPoolItem aOld( RES_ALT_TEXT_CHANGED, aAlternateText );
        SwStringMsgPoolItem aNew( RES_ALT_TEXT_CHANGED, rTxt );
        aAlternateText = rTxt;
        Modify( &aOld, &aNew );
    }
    else
    {
        aAlternateText = rTxt;
    }
}

<|endoftext|>


<commit_before><commit_msg>Headers/Footers: set only the main color and play with luminance for the other<commit_after><|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2009-2014, MAV'RIC Development Team
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name 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.
 ******************************************************************************/

/*******************************************************************************
 * \file gps_telemetry.cpp
 *
 * \author MAV'RIC Team
 * \author Nicolas Dousse
 *
 * \brief GPS telemetry
 *
 ******************************************************************************/

#include "gps_telemetry.hpp"

extern "C"
{
	#include "time_keeper.h"
	#include "maths.h"
	#include "constants.h"
}

void gps_telemetry_send_raw(const Gps* gps, const mavlink_stream_t* mavlink_stream, mavlink_message_t* msg)
{
	global_position_t global_position = gps->global_position();
	float ground_speed = maths_fast_sqrt( gps->global_velocity()[X] * gps->global_velocity()[X]
										+ gps->global_velocity()[Y] * gps->global_velocity()[Y]
										+ gps->global_velocity()[Z] * gps->global_velocity()[Z]	 );
	mavlink_msg_gps_raw_int_pack(	mavlink_stream->sysid,
									mavlink_stream->compid,
									msg,
									gps->last_update_us(),
									gps->fix(),
									global_position.latitude  * 10000000.0f,
									global_position.longitude * 10000000.0f,
									global_position.altitude  * 1000.0f,
									gps->horizontal_position_accuracy() * 100.0f,
									gps->horizontal_position_accuracy() * 100.0f,
									ground_speed * 100.0f,
									gps->heading() * 100.0f,
									gps->num_sats()	);
}<commit_msg>Send also gps vertical accuracy<commit_after>/*******************************************************************************
 * Copyright (c) 2009-2014, MAV'RIC Development Team
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * 3. Neither the name 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.
 ******************************************************************************/

/*******************************************************************************
 * \file gps_telemetry.cpp
 *
 * \author MAV'RIC Team
 * \author Nicolas Dousse
 *
 * \brief GPS telemetry
 *
 ******************************************************************************/

#include "gps_telemetry.hpp"

extern "C"
{
	#include "time_keeper.h"
	#include "maths.h"
	#include "constants.h"
}

void gps_telemetry_send_raw(const Gps* gps, const mavlink_stream_t* mavlink_stream, mavlink_message_t* msg)
{
	global_position_t global_position = gps->global_position();
	float ground_speed = maths_fast_sqrt( gps->global_velocity()[X] * gps->global_velocity()[X]
										+ gps->global_velocity()[Y] * gps->global_velocity()[Y]
										+ gps->global_velocity()[Z] * gps->global_velocity()[Z]	 );
	mavlink_msg_gps_raw_int_pack(	mavlink_stream->sysid,
									mavlink_stream->compid,
									msg,
									gps->last_update_us(),
									gps->fix(),
									global_position.latitude  * 10000000.0f,
									global_position.longitude * 10000000.0f,
									global_position.altitude  * 1000.0f,
									gps->horizontal_position_accuracy() * 100.0f,
									gps->vertical_position_accuracy() * 100.0f,
									ground_speed * 100.0f,
									gps->heading() * 100.0f,
									gps->num_sats()	);
}<|endoftext|>


<commit_before>/*
  A hacky replacement for backtrace_symbols in glibc

  backtrace_symbols in glibc looks up symbols using dladdr which is limited in
  the symbols that it sees. libbacktracesymbols opens the executable and shared
  libraries using libbfd and will look up backtrace information using the symbol
  table and the dwarf line information.

  It may make more sense for this program to use libelf instead of libbfd.
  However, I have not investigated that yet.

  Derived from addr2line.c from GNU Binutils by Jeff Muizelaar

  Copyright 2007 Jeff Muizelaar
*/

/* addr2line.c -- convert addresses to line number and function name
   Copyright 1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
   Contributed by Ulrich Lauther <Ulrich.Lauther@mchp.siemens.de>

   This file was part of GNU Binutils.

   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, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.  */

#ifdef HASBFD

#include "util/Result.h"
#include "FindFile.h" // GetBinaryFilename
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include "Debug.h"
#include "util/StringConv.h"

/* 2 characters for each byte, plus 1 each for 0, x, and NULL */
#define PTRSTR_LEN (sizeof(void *) * 2 + 3)

#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#ifdef __APPLE__
#include <bfd.h>
#include <dlfcn.h>
#include <mach-o/dyld.h>
#else
#include <bfd.h>
#include <libiberty.h>
#include <dlfcn.h>
#include <link.h>
#endif

#if 0

void (*dbfd_init)(void);
bfd_vma (*dbfd_scan_vma)(const char *string, const char **end, int base);
bfd* (*dbfd_openr)(const char *filename, const char *target);
bfd_boolean (*dbfd_check_format)(bfd *abfd, bfd_format format);
bfd_boolean (*dbfd_check_format_matches)(bfd *abfd, bfd_format format, char ***matching);
bfd_boolean (*dbfd_close)(bfd *abfd);
bfd_boolean (*dbfd_map_over_sections)(bfd *abfd, void (*func)(bfd *abfd, asection *sect, void *obj),
		void *obj);
#define bfd_init dbfd_init

static void load_funcs(void)
{
	void * handle = dlopen("libbfd.so", RTLD_NOW);
	dbfd_init = dlsym(handle, "bfd_init");
	dbfd_scan_vma = dlsym(handle, "bfd_scan_vma");
	dbfd_openr = dlsym(handle, "bfd_openr");
	dbfd_check_format = dlsym(handle, "bfd_check_format");
	dbfd_check_format_matches = dlsym(handle, "bfd_check_format_matches");
	dbfd_close = dlsym(handle, "bfd_close");
	dbfd_map_over_sections = dlsym(handle, "bfd_map_over_sections");
}

#endif

static asymbol **syms;		/* Symbol table.  */

static Result slurp_symtab(bfd * abfd);
static void find_address_in_section(bfd *abfd, asection *section, void *data);

/* Read in the symbol table.  */

static Result slurp_symtab(bfd * abfd)
{
	if ((bfd_get_file_flags(abfd) & HAS_SYMS) == 0)
		return "file has no symtab";

	unsigned int size = 0;
	long symcount = bfd_read_minisymbols(abfd, false, (void**) &syms, &size);
	if (symcount == 0)
		symcount = bfd_read_minisymbols(abfd, true /* dynamic */ ,
						(void**) &syms, &size);

	if (symcount < 0)
		return "error getting minisymbols";

	if (symcount == 0)
		return "no minisymbols found";

	return true;
}

/* These global variables are used to pass information between
   translate_addresses and find_address_in_section.  */

static bfd_vma pc;
static const char *filename;
static const char *functionname;
static unsigned int line;
static bool found = false;
static bool sectionFound = false;

/* Look for an address in a section.  This is called via
   bfd_map_over_sections.  */

static void find_address_in_section(bfd *abfd, asection *section, void *data __attribute__ ((__unused__)) )
{
	if (found)
		return;

	if ((bfd_get_section_flags(abfd, section) & SEC_ALLOC) == 0)
		return;

	bfd_vma vma = bfd_get_section_vma(abfd, section);
	bfd_size_type size = bfd_section_size(abfd, section);

	//std::cout << "section: " << vma << " - " << (vma + size) << ", searched for " << pc << std::endl;

	if (pc < vma)
		return;

	if (pc >= vma + size)
		return;

	sectionFound = true;
	found = bfd_find_nearest_line(abfd, section, syms, pc - vma,
				      &filename, &functionname, &line);
}

static std::string translate_addresses_buf(bfd * abfd, bfd_vma addr)
{
	std::ostringstream ret;

	pc = addr;
	sectionFound = false;
	found = false;
	bfd_map_over_sections(abfd, find_address_in_section, (PTR) NULL);

	if (!found) {
		ret.setf( std::ios::hex, std::ios::basefield );
		ret.setf( std::ios::showbase );
		ret << "[" << (long long unsigned int) addr << "] ";
		if(sectionFound) ret << "<function not found>";
		else ret << "<section not found>";

	} else {
		if (filename != NULL) {
			char *h = strrchr(filename, '/');
			if (h != NULL)
				filename = h + 1;

			ret << filename;
		}
		else
			ret << "<unknown file>";

		ret << ":" << line << "\t";

		if (functionname == NULL || *functionname == '\0')
			ret << "<unknown function>";
		else
			ret << functionname << "()";
	}

	return ret.str();
}
/* Process a file.  */

static Result process_file(const std::string& file_name, bfd_vma addr, std::string& ret_buf)
{
	bfd *abfd;
	char **matching;

	abfd = bfd_openr(file_name.c_str(), NULL);

	if (abfd == NULL)
		return "can't open " + file_name;

	if (bfd_check_format(abfd, bfd_archive))
		return "invalid format: " + file_name;

	if (!bfd_check_format_matches(abfd, bfd_object, &matching)) {
		//bfd_nonfatal(bfd_get_filename(abfd));
		if (bfd_get_error() ==
		    bfd_error_file_ambiguously_recognized) {
			//list_matching_formats(matching);
			free(matching);
		}
		return "format does not match: " + file_name;
	}

	if(NegResult r = slurp_symtab(abfd))
		return "slurp_symtab: " + r.res.humanErrorMsg;

	ret_buf = translate_addresses_buf(abfd, addr);

	free (syms);
	syms = NULL;

	bfd_close(abfd);
	return true;
}

#define MAX_DEPTH 16

struct file_match {
	const char *file;
	void *address;
	void *base;
	void *hdr;
};

#ifndef __APPLE__
static int find_matching_file(struct dl_phdr_info *info,
		size_t size, void *data)
{
	struct file_match *match = (struct file_match*) data;
	/* This code is modeled from Gfind_proc_info-lsb.c:callback() from libunwind */
	long n;
	const ElfW(Phdr) *phdr;
	ElfW(Addr) load_base = info->dlpi_addr;
	phdr = info->dlpi_phdr;
	for (n = info->dlpi_phnum; --n >= 0; phdr++) {
		if (phdr->p_type == PT_LOAD) {
			ElfW(Addr) vaddr = phdr->p_vaddr + load_base;
			if (match->address >= vaddr && match->address < vaddr + phdr->p_memsz) {
				/* we found a match */
				match->file = info->dlpi_name;
				match->base = info->dlpi_addr;
			}
		}
	}
	return 0;
}
#else
static bool
ptr_is_in_exe(const void *ptr, intptr_t& offset, uintptr_t& vmaddr, std::string& image_name)
{
	uint32_t i, count = _dyld_image_count();

	for (i = 0; i < count; i++) {
		const struct mach_header *header = _dyld_get_image_header(i);
		offset = _dyld_get_image_vmaddr_slide(i);
		//notes << i << "," << offset << ": " << _dyld_get_image_name(i) << endl;

		uint32_t j = 0;
		struct load_command* cmd = (struct load_command*)((char *)header + sizeof(struct mach_header));
		if(header->magic == MH_MAGIC_64)
			cmd = (struct load_command*)((char *)header + sizeof(struct mach_header_64));
		//struct load_command* cmd_end = cmd + header->sizeofcmds;

		while (j < header->ncmds) {
			if (cmd->cmd == LC_SEGMENT) {
				struct segment_command* seg = (struct segment_command*)cmd;
				if (((intptr_t)ptr >= (seg->vmaddr + offset)) && ((intptr_t)ptr < (seg->vmaddr + offset + seg->vmsize))) {
					vmaddr = seg->vmaddr;
					image_name = _dyld_get_image_name(i);
					return true;
				}
			}
			if (cmd->cmd == LC_SEGMENT_64) {
				struct segment_command_64* seg = (struct segment_command_64*)cmd;
				if (((uintptr_t)ptr >= (seg->vmaddr + offset)) && ((uintptr_t)ptr < (seg->vmaddr + offset + seg->vmsize))) {
					vmaddr = seg->vmaddr;
					image_name = _dyld_get_image_name(i);
					return true;
				}
			}

			j++;
			cmd = (struct load_command*)((char*)cmd + cmd->cmdsize);

			//if(cmd >= cmd_end || cmd->cmdsize == 0)
				// this is a strange case but it seems happening
			//	break;
		}
	}

	return false;
}
#endif

char **backtrace_symbols(void *const *buffer, int size)
{
	int stack_depth = size - 1;
	int x,y;
	/* discard calling function */
	int total = 0;

	char **final;
	char *f_strings;

	std::vector<std::string> locations(stack_depth + 1);

	bfd_init();
	for(x=stack_depth, y=0; x>=0; x--, y++){
		const void* xaddr = buffer[x];
		bfd_vma addr = (bfd_vma)xaddr;
		Result r = true;
#ifndef __APPLE__
		struct file_match match;
		match.address = buffer[x];
		dl_iterate_phdr(find_matching_file, &match);
		addr = xaddr - match.base;
		if (match.file && strlen(match.file))
			r = process_file(match.file, addr, locations[x]);
		else
			r = process_file(GetBinaryFilename(), addr, locations[x]);
#else
		/*Dl_info info;
		if(dladdr(xaddr, &info)) {
			//notes << "addr " << xaddr << ": " << info.dli_fname << "," << info.dli_sname << endl;
			//notes << info.dli_fname << ": " << info.dli_fbase << endl;
			addr = bfd_vma((char*)xaddr - (char*)info.dli_fbase);
			r = process_file(info.dli_fname, addr, locations[x]);
		}
		else r = "dladdr failed";*/
		intptr_t offset;
		uintptr_t vmaddr;
		std::string image_name;
		if(ptr_is_in_exe(xaddr, offset, vmaddr, image_name)) {
			//notes << "addr " << xaddr << ": " << image_name << ", " << vmaddr << ", " << offset << endl;
			addr = bfd_vma((char*)xaddr - vmaddr);
			r = process_file(image_name, addr, locations[x]);
		}
		else r = "ptr " + hex((intptr_t)xaddr) + " not found";
#endif
		if(!r)
			locations[x] = "<" + r.humanErrorMsg + ">";
		total += locations[x].size() + 1;
	}

	/* allocate the array of char* we are going to return and extra space for
	 * all of the strings */
	final = (char**)malloc(total + (stack_depth + 1) * sizeof(char*));
	/* get a pointer to the extra space */
	f_strings = (char*)(final + stack_depth + 1);

	/* fill in all of strings and pointers */
	for(x=stack_depth; x>=0; x--){
		strcpy(f_strings, locations[x].c_str());
		final[x] = f_strings;
		f_strings += strlen(f_strings) + 1;
	}

	return final;
}

void
backtrace_symbols_fd(void *const *buffer, int size, int fd)
{
        int j;
        char **strings;

        strings = backtrace_symbols(buffer, size);
		if (strings == NULL) return;

        for (j = 0; j < size; j++)
		printf("%s\n", strings[j]);

        free(strings);
}

// Not sure on this. Linking failed on Mac.
// Found it here: http://www.mail-archive.com/uclinux-dev@uclinux.org/msg02347.html
#ifndef HAVE_LIBINTL_DGETTEXT
extern "C"
const char *libintl_dgettext (const char *domain, const char *msg)
{
  return msg;
}
#endif /* !HAVE_LIBINTL_DGETTEXT */

#endif // HASBFD
<commit_msg>dladdr fallback<commit_after>/*
  A hacky replacement for backtrace_symbols in glibc

  backtrace_symbols in glibc looks up symbols using dladdr which is limited in
  the symbols that it sees. libbacktracesymbols opens the executable and shared
  libraries using libbfd and will look up backtrace information using the symbol
  table and the dwarf line information.

  It may make more sense for this program to use libelf instead of libbfd.
  However, I have not investigated that yet.

  Derived from addr2line.c from GNU Binutils by Jeff Muizelaar

  Copyright 2007 Jeff Muizelaar
*/

/* addr2line.c -- convert addresses to line number and function name
   Copyright 1997, 1998, 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
   Contributed by Ulrich Lauther <Ulrich.Lauther@mchp.siemens.de>

   This file was part of GNU Binutils.

   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, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.  */

#ifdef HASBFD

#include "util/Result.h"
#include "FindFile.h" // GetBinaryFilename
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include "Debug.h"
#include "util/StringConv.h"

/* 2 characters for each byte, plus 1 each for 0, x, and NULL */
#define PTRSTR_LEN (sizeof(void *) * 2 + 3)

#define _GNU_SOURCE
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#ifdef __APPLE__
#include <bfd.h>
#include <dlfcn.h>
#include <mach-o/dyld.h>
#else
#include <bfd.h>
#include <libiberty.h>
#include <dlfcn.h>
#include <link.h>
#endif

#if 0

void (*dbfd_init)(void);
bfd_vma (*dbfd_scan_vma)(const char *string, const char **end, int base);
bfd* (*dbfd_openr)(const char *filename, const char *target);
bfd_boolean (*dbfd_check_format)(bfd *abfd, bfd_format format);
bfd_boolean (*dbfd_check_format_matches)(bfd *abfd, bfd_format format, char ***matching);
bfd_boolean (*dbfd_close)(bfd *abfd);
bfd_boolean (*dbfd_map_over_sections)(bfd *abfd, void (*func)(bfd *abfd, asection *sect, void *obj),
		void *obj);
#define bfd_init dbfd_init

static void load_funcs(void)
{
	void * handle = dlopen("libbfd.so", RTLD_NOW);
	dbfd_init = dlsym(handle, "bfd_init");
	dbfd_scan_vma = dlsym(handle, "bfd_scan_vma");
	dbfd_openr = dlsym(handle, "bfd_openr");
	dbfd_check_format = dlsym(handle, "bfd_check_format");
	dbfd_check_format_matches = dlsym(handle, "bfd_check_format_matches");
	dbfd_close = dlsym(handle, "bfd_close");
	dbfd_map_over_sections = dlsym(handle, "bfd_map_over_sections");
}

#endif

static asymbol **syms;		/* Symbol table.  */

static Result slurp_symtab(bfd * abfd);
static void find_address_in_section(bfd *abfd, asection *section, void *data);

/* Read in the symbol table.  */

static Result slurp_symtab(bfd * abfd)
{
	if ((bfd_get_file_flags(abfd) & HAS_SYMS) == 0)
		return "file has no symtab";

	unsigned int size = 0;
	long symcount = bfd_read_minisymbols(abfd, false, (void**) &syms, &size);
	if (symcount == 0)
		symcount = bfd_read_minisymbols(abfd, true /* dynamic */ ,
						(void**) &syms, &size);

	if (symcount < 0)
		return "error getting minisymbols";

	if (symcount == 0)
		return "no minisymbols found";

	return true;
}

/* These global variables are used to pass information between
   translate_addresses and find_address_in_section.  */

static bfd_vma pc;
static const char *filename;
static const char *functionname;
static unsigned int line;
static bool found = false;
static bool sectionFound = false;

/* Look for an address in a section.  This is called via
   bfd_map_over_sections.  */

static void find_address_in_section(bfd *abfd, asection *section, void *data __attribute__ ((__unused__)) )
{
	if (found)
		return;

	if ((bfd_get_section_flags(abfd, section) & SEC_ALLOC) == 0)
		return;

	bfd_vma vma = bfd_get_section_vma(abfd, section);
	bfd_size_type size = bfd_section_size(abfd, section);

	//std::cout << "section: " << vma << " - " << (vma + size) << ", searched for " << pc << std::endl;

	if (pc < vma)
		return;

	if (pc >= vma + size)
		return;

	sectionFound = true;
	found = bfd_find_nearest_line(abfd, section, syms, pc - vma,
				      &filename, &functionname, &line);
}

static std::string translate_addresses_buf(bfd * abfd, bfd_vma addr)
{
	std::ostringstream ret;

	pc = addr;
	sectionFound = false;
	found = false;
	bfd_map_over_sections(abfd, find_address_in_section, (PTR) NULL);

	if (!found) {
		ret.setf( std::ios::hex, std::ios::basefield );
		ret.setf( std::ios::showbase );
		ret << "[" << (long long unsigned int) addr << "] ";
		if(sectionFound) ret << "<function not found>";
		else ret << "<section not found>";

	} else {
		if (filename != NULL) {
			char *h = strrchr(filename, '/');
			if (h != NULL)
				filename = h + 1;

			ret << filename;
		}
		else
			ret << "<unknown file>";

		ret << ":" << line << "\t";

		if (functionname == NULL || *functionname == '\0')
			ret << "<unknown function>";
		else
			ret << functionname << "()";
	}

	return ret.str();
}
/* Process a file.  */

static Result process_file(const std::string& file_name, bfd_vma addr, std::string& ret_buf)
{
	bfd *abfd;
	char **matching;

	abfd = bfd_openr(file_name.c_str(), NULL);

	if (abfd == NULL)
		return "can't open " + file_name;

	if (bfd_check_format(abfd, bfd_archive))
		return "invalid format: " + file_name;

	if (!bfd_check_format_matches(abfd, bfd_object, &matching)) {
		//bfd_nonfatal(bfd_get_filename(abfd));
		if (bfd_get_error() ==
		    bfd_error_file_ambiguously_recognized) {
			//list_matching_formats(matching);
			free(matching);
		}
		return "format does not match: " + file_name;
	}

	if(NegResult r = slurp_symtab(abfd))
		return "slurp_symtab: " + r.res.humanErrorMsg;

	ret_buf = translate_addresses_buf(abfd, addr);

	free (syms);
	syms = NULL;

	bfd_close(abfd);
	return true;
}

#define MAX_DEPTH 16

struct file_match {
	const char *file;
	void *address;
	void *base;
	void *hdr;
};

#ifndef __APPLE__
static int find_matching_file(struct dl_phdr_info *info,
		size_t size, void *data)
{
	struct file_match *match = (struct file_match*) data;
	/* This code is modeled from Gfind_proc_info-lsb.c:callback() from libunwind */
	long n;
	const ElfW(Phdr) *phdr;
	ElfW(Addr) load_base = info->dlpi_addr;
	phdr = info->dlpi_phdr;
	for (n = info->dlpi_phnum; --n >= 0; phdr++) {
		if (phdr->p_type == PT_LOAD) {
			ElfW(Addr) vaddr = phdr->p_vaddr + load_base;
			if (match->address >= vaddr && match->address < vaddr + phdr->p_memsz) {
				/* we found a match */
				match->file = info->dlpi_name;
				match->base = info->dlpi_addr;
			}
		}
	}
	return 0;
}
#else
static bool
ptr_is_in_exe(const void *ptr, intptr_t& offset, uintptr_t& vmaddr, std::string& image_name)
{
	uint32_t i, count = _dyld_image_count();

	for (i = 0; i < count; i++) {
		const struct mach_header *header = _dyld_get_image_header(i);
		offset = _dyld_get_image_vmaddr_slide(i);
		//notes << i << "," << offset << ": " << _dyld_get_image_name(i) << endl;

		uint32_t j = 0;
		struct load_command* cmd = (struct load_command*)((char *)header + sizeof(struct mach_header));
		if(header->magic == MH_MAGIC_64)
			cmd = (struct load_command*)((char *)header + sizeof(struct mach_header_64));
		//struct load_command* cmd_end = cmd + header->sizeofcmds;

		while (j < header->ncmds) {
			if (cmd->cmd == LC_SEGMENT) {
				struct segment_command* seg = (struct segment_command*)cmd;
				if (((intptr_t)ptr >= (seg->vmaddr + offset)) && ((intptr_t)ptr < (seg->vmaddr + offset + seg->vmsize))) {
					vmaddr = seg->vmaddr;
					image_name = _dyld_get_image_name(i);
					return true;
				}
			}
			if (cmd->cmd == LC_SEGMENT_64) {
				struct segment_command_64* seg = (struct segment_command_64*)cmd;
				if (((uintptr_t)ptr >= (seg->vmaddr + offset)) && ((uintptr_t)ptr < (seg->vmaddr + offset + seg->vmsize))) {
					vmaddr = seg->vmaddr;
					image_name = _dyld_get_image_name(i);
					return true;
				}
			}

			j++;
			cmd = (struct load_command*)((char*)cmd + cmd->cmdsize);

			//if(cmd >= cmd_end || cmd->cmdsize == 0)
				// this is a strange case but it seems happening
			//	break;
		}
	}

	return false;
}
#endif

char **backtrace_symbols(void *const *buffer, int size)
{
	int stack_depth = size - 1;
	int x,y;
	/* discard calling function */
	int total = 0;

	char **final;
	char *f_strings;

	std::vector<std::string> locations(stack_depth + 1);

	bfd_init();
	for(x=stack_depth, y=0; x>=0; x--, y++){
		const void* xaddr = buffer[x];
		bfd_vma addr = (bfd_vma)xaddr;
		Result r = true;
#ifndef __APPLE__
		struct file_match match;
		match.address = buffer[x];
		dl_iterate_phdr(find_matching_file, &match);
		addr = xaddr - match.base;
		if (match.file && strlen(match.file))
			r = process_file(match.file, addr, locations[x]);
		else
			r = process_file(GetBinaryFilename(), addr, locations[x]);
#else
		intptr_t offset;
		uintptr_t vmaddr;
		std::string image_name;
		if(ptr_is_in_exe(xaddr, offset, vmaddr, image_name)) {
			//notes << "addr " << xaddr << ": " << image_name << ", " << vmaddr << ", " << offset << endl;
			addr = bfd_vma((char*)xaddr - vmaddr);
			r = process_file(image_name, addr, locations[x]);
		}
		else r = "image not found";
#endif
		if(!r) {
			locations[x] = "[0x" + hex((uintptr_t)xaddr) + "] <" + r.humanErrorMsg + ">";

			// we might be able to use dladdr as fallback
			Dl_info info;
			if(dladdr(xaddr, &info))
				locations[x] += " " + GetBaseFilename(info.dli_fname) + ":" + info.dli_sname;
		}
		total += locations[x].size() + 1;
	}

	/* allocate the array of char* we are going to return and extra space for
	 * all of the strings */
	final = (char**)malloc(total + (stack_depth + 1) * sizeof(char*));
	/* get a pointer to the extra space */
	f_strings = (char*)(final + stack_depth + 1);

	/* fill in all of strings and pointers */
	for(x=stack_depth; x>=0; x--){
		strcpy(f_strings, locations[x].c_str());
		final[x] = f_strings;
		f_strings += strlen(f_strings) + 1;
	}

	return final;
}

void
backtrace_symbols_fd(void *const *buffer, int size, int fd)
{
        int j;
        char **strings;

        strings = backtrace_symbols(buffer, size);
		if (strings == NULL) return;

        for (j = 0; j < size; j++)
		printf("%s\n", strings[j]);

        free(strings);
}

// Not sure on this. Linking failed on Mac.
// Found it here: http://www.mail-archive.com/uclinux-dev@uclinux.org/msg02347.html
#ifndef HAVE_LIBINTL_DGETTEXT
extern "C"
const char *libintl_dgettext (const char *domain, const char *msg)
{
  return msg;
}
#endif /* !HAVE_LIBINTL_DGETTEXT */

#endif // HASBFD
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CG_FEM_HH
#define DUNE_GDT_SPACES_CG_FEM_HH

#include <memory>

#include <dune/common/deprecated.hh>

#if HAVE_DUNE_FEM
#include <dune/fem/space/common/functionspace.hh>
#include <dune/fem/space/lagrange/space.hh>
#endif // HAVE_DUNE_FEM

#include <dune/stuff/common/type_utils.hh>

#include <dune/gdt/spaces/parallel.hh>

#include "../../mapper/fem.hh"
#include "../../basefunctionset/fem.hh"

#include "interface.hh"
#include "../constraints.hh"

namespace Dune {
namespace GDT {
namespace Spaces {
namespace CG {

#if HAVE_DUNE_FEM

// forward, to be used in the traits and to allow for specialization
template <class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class FemBased
{
  static_assert(Dune::AlwaysFalse<GridPartImp>::value, "Untested for these dimensions!");
};

template <class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols>
class FemBasedTraits
{
public:
  typedef FemBased<GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
  typedef GridPartImp GridPartType;
  typedef typename GridPartType::GridViewType GridViewType;
  static const int polOrder    = polynomialOrder;
  static const bool continuous = true;
  static_assert(polOrder >= 1, "Wrong polOrder given!");

private:
  typedef typename GridPartType::ctype DomainFieldType;
  static const size_t dimDomain = GridPartType::dimension;

public:
  typedef RangeFieldImp RangeFieldType;

private:
  typedef Dune::Fem::FunctionSpace<DomainFieldType, RangeFieldType, dimDomain, rangeDim> FunctionSpaceType;

public:
  typedef Dune::Fem::LagrangeDiscreteFunctionSpace<FunctionSpaceType, GridPartType, polOrder> BackendType;
  typedef Mapper::FemDofWrapper<typename BackendType::BlockMapperType, 1> MapperType;
  typedef typename GridPartType::template Codim<0>::EntityType EntityType;
  typedef BaseFunctionSet::FemWrapper<typename BackendType::ShapeFunctionSetType, EntityType, DomainFieldType,
                                      dimDomain, RangeFieldType, rangeDim, rangeDimCols> BaseFunctionSetType;
  static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::part;
  static const bool needs_grid_view                       = false;
  typedef CommunicationChooser<GridViewType, false> CommunicationChooserType;
  typedef typename CommunicationChooserType::Type CommunicatorType;
}; // class SpaceWrappedFemContinuousLagrangeTraits

// untested for the vector-valued case, especially Spaces::CGInterface
template <class GridPartImp, int polynomialOrder, class RangeFieldImp>
class FemBased<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>
    : public Spaces::CGInterface<FemBasedTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>,
                                 GridPartImp::dimension, 1, 1>
{
  typedef Spaces::CGInterface<FemBasedTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>, GridPartImp::dimension,
                              1, 1> BaseType;
  typedef FemBased<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1> ThisType;

public:
  typedef FemBasedTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;

  static const int polOrder        = Traits::polOrder;
  static const size_t dimDomain    = BaseType::dimDomain;
  static const size_t dimRange     = BaseType::dimRange;
  static const size_t dimRangeCols = BaseType::dimRangeCols;

  typedef typename Traits::GridPartType GridPartType;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::MapperType MapperType;
  typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
  typedef typename Traits::EntityType EntityType;

private:
  typedef typename Traits::CommunicationChooserType CommunicationChooserType;

public:
  typedef typename Traits::CommunicatorType CommunicatorType;

  using typename BaseType::DomainType;
  using typename BaseType::BoundaryInfoType;

  explicit FemBased(GridPartType gridP)
    : gridPart_(new GridPartType(gridP))
    , gridView_(new GridViewType(gridPart_->gridView()))
    , backend_(new BackendType(*gridPart_))
    , mapper_(new MapperType(backend_->blockMapper()))
    , communicator_(CommunicationChooserType::create(*gridView_))
  {
  }

  FemBased(const ThisType& other) = default;
  explicit FemBased(ThisType&& source) = default;

  ThisType& operator=(const ThisType& other) = delete;
  ThisType& operator=(ThisType&& source) = delete;

  const GridPartType& grid_part() const
  {
    return *gridPart_;
  }

  const GridViewType& grid_view() const
  {
    return *gridView_;
  }

  const BackendType& backend() const
  {
    return *backend_;
  }

  const MapperType& mapper() const
  {
    return *mapper_;
  }

  std::vector<DomainType> lagrange_points(const EntityType& entity) const
  {
    return BaseType::lagrange_points_order_1(entity);
  }

  std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
  {
    return BaseType::local_dirichlet_DoFs_order_1(entity, boundaryInfo);
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(*backend_, entity);
  }

  CommunicatorType& communicator() const
  {
    // no need to prepare the communicator, since we are not pdelab based
    return *communicator_;
  }

private:
  std::shared_ptr<GridPartType> gridPart_;
  const std::shared_ptr<const GridViewType> gridView_;
  const std::shared_ptr<const BackendType> backend_;
  const std::shared_ptr<const MapperType> mapper_;
  mutable std::shared_ptr<CommunicatorType> communicator_;
}; // class FemBased< ..., 1 >

#else // HAVE_DUNE_FEM

template <class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class FemBased
{
  static_assert(Dune::AlwaysFalse<GridPartImp>::value, "You are missing dune-fem!");
};

#endif // HAVE_DUNE_FEM

} // namespace CG
} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CG_FEM_HH
<commit_msg>[spaces.cg.fem] enable for dimRange >= 1<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACES_CG_FEM_HH
#define DUNE_GDT_SPACES_CG_FEM_HH

#include <memory>

#include <dune/common/deprecated.hh>

#if HAVE_DUNE_FEM
#include <dune/fem/space/common/functionspace.hh>
#include <dune/fem/space/lagrange/space.hh>
#endif // HAVE_DUNE_FEM

#include <dune/stuff/common/type_utils.hh>

#include <dune/gdt/spaces/parallel.hh>

#include "../../mapper/fem.hh"
#include "../../basefunctionset/fem.hh"

#include "interface.hh"
#include "../constraints.hh"

namespace Dune {
namespace GDT {
namespace Spaces {
namespace CG {

#if HAVE_DUNE_FEM

// forward, to be used in the traits and to allow for specialization
template <class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class FemBased
{
  static_assert(Dune::AlwaysFalse<GridPartImp>::value, "Untested for these dimensions!");
};

template <class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols>
class FemBasedTraits
{
public:
  typedef FemBased<GridPartImp, polynomialOrder, RangeFieldImp, rangeDim, rangeDimCols> derived_type;
  typedef GridPartImp GridPartType;
  typedef typename GridPartType::GridViewType GridViewType;
  static const int polOrder    = polynomialOrder;
  static const bool continuous = true;
  static_assert(polOrder >= 1, "Wrong polOrder given!");

private:
  typedef typename GridPartType::ctype DomainFieldType;
  static const size_t dimDomain = GridPartType::dimension;

public:
  typedef RangeFieldImp RangeFieldType;

private:
  typedef Dune::Fem::FunctionSpace<DomainFieldType, RangeFieldType, dimDomain, rangeDim> FunctionSpaceType;

public:
  typedef Dune::Fem::LagrangeDiscreteFunctionSpace<FunctionSpaceType, GridPartType, polOrder> BackendType;
  typedef Mapper::FemDofWrapper<typename BackendType::BlockMapperType, BackendType::Traits::localBlockSize> MapperType;
  typedef typename GridPartType::template Codim<0>::EntityType EntityType;
  typedef BaseFunctionSet::FemWrapper<typename BackendType::ShapeFunctionSetType, EntityType, DomainFieldType,
                                      dimDomain, RangeFieldType, rangeDim, rangeDimCols> BaseFunctionSetType;
  static const Stuff::Grid::ChoosePartView part_view_type = Stuff::Grid::ChoosePartView::part;
  static const bool needs_grid_view                       = false;
  typedef CommunicationChooser<GridViewType, false> CommunicationChooserType;
  typedef typename CommunicationChooserType::Type CommunicatorType;
}; // class FemBasedTraits

// untested for the vector-valued case, especially Spaces::CGInterface
template <class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t r>
class FemBased<GridPartImp, polynomialOrder, RangeFieldImp, r, 1>
    : public Spaces::CGInterface<FemBasedTraits<GridPartImp, polynomialOrder, RangeFieldImp, r, 1>,
                                 GridPartImp::dimension, r, 1>
{
  typedef Spaces::CGInterface<FemBasedTraits<GridPartImp, polynomialOrder, RangeFieldImp, r, 1>, GridPartImp::dimension,
                              r, 1> BaseType;
  typedef FemBased<GridPartImp, polynomialOrder, RangeFieldImp, r, 1> ThisType;

public:
  typedef FemBasedTraits<GridPartImp, polynomialOrder, RangeFieldImp, r, 1> Traits;

  static const int polOrder        = Traits::polOrder;
  static const size_t dimDomain    = BaseType::dimDomain;
  static const size_t dimRange     = BaseType::dimRange;
  static const size_t dimRangeCols = BaseType::dimRangeCols;

  typedef typename Traits::GridPartType GridPartType;
  typedef typename Traits::GridViewType GridViewType;
  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::MapperType MapperType;
  typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
  typedef typename Traits::EntityType EntityType;

private:
  typedef typename Traits::CommunicationChooserType CommunicationChooserType;

public:
  typedef typename Traits::CommunicatorType CommunicatorType;

  using typename BaseType::DomainType;
  using typename BaseType::BoundaryInfoType;

  explicit FemBased(GridPartType gridP)
    : gridPart_(new GridPartType(gridP))
    , gridView_(new GridViewType(gridPart_->gridView()))
    , backend_(new BackendType(*gridPart_))
    , mapper_(new MapperType(backend_->blockMapper()))
    , communicator_(CommunicationChooserType::create(*gridView_))
  {
  }

  FemBased(const ThisType& other) = default;
  explicit FemBased(ThisType&& source) = default;

  ThisType& operator=(const ThisType& other) = delete;
  ThisType& operator=(ThisType&& source) = delete;

  const GridPartType& grid_part() const
  {
    return *gridPart_;
  }

  const GridViewType& grid_view() const
  {
    return *gridView_;
  }

  const BackendType& backend() const
  {
    return *backend_;
  }

  const MapperType& mapper() const
  {
    return *mapper_;
  }

  std::vector<DomainType> lagrange_points(const EntityType& entity) const
  {
    return BaseType::lagrange_points_order_1(entity);
  }

  std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const
  {
    return BaseType::local_dirichlet_DoFs_order_1(entity, boundaryInfo);
  }

  BaseFunctionSetType base_function_set(const EntityType& entity) const
  {
    return BaseFunctionSetType(*backend_, entity);
  }

  CommunicatorType& communicator() const
  {
    // no need to prepare the communicator, since we are not pdelab based
    return *communicator_;
  }

private:
  std::shared_ptr<GridPartType> gridPart_;
  const std::shared_ptr<const GridViewType> gridView_;
  const std::shared_ptr<const BackendType> backend_;
  const std::shared_ptr<const MapperType> mapper_;
  mutable std::shared_ptr<CommunicatorType> communicator_;
}; // class FemBased< ..., 1 >

#else // HAVE_DUNE_FEM

template <class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1>
class FemBased
{
  static_assert(Dune::AlwaysFalse<GridPartImp>::value, "You are missing dune-fem!");
};

#endif // HAVE_DUNE_FEM

} // namespace CG
} // namespace Spaces
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CG_FEM_HH
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          frame.cpp
* Purpose:       Implementation of wxExFrameWithHistory class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/stdpaths.h>
#include <wx/extension/report/report.h>

BEGIN_EVENT_TABLE(wxExFrameWithHistory, wxExManagedFrame)
  EVT_CLOSE(wxExFrameWithHistory::OnClose)
  EVT_IDLE(wxExFrameWithHistory::OnIdle)
  EVT_MENU(wxID_OPEN, wxExFrameWithHistory::OnCommand)
  EVT_MENU(wxID_PREFERENCES, wxExFrameWithHistory::OnCommand)
  EVT_MENU(ID_TERMINATED_PROCESS, wxExFrameWithHistory::OnCommand)
  EVT_MENU_RANGE(
    ID_EXTENSION_REPORT_LOWEST,
    ID_EXTENSION_REPORT_HIGHEST,
    wxExFrameWithHistory::OnCommand)
  EVT_UPDATE_UI(ID_VIEW_STATUSBAR, wxExFrameWithHistory::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_TOOLBAR, wxExFrameWithHistory::OnUpdateUI)
END_EVENT_TABLE()

wxExFrameWithHistory::wxExFrameWithHistory(wxWindow* parent,
  wxWindowID id,
  const wxString& title,
  size_t maxFiles,
  size_t maxProjects,
  int style)
  : wxExManagedFrame(parent, id, title, style)
  , m_FileHistory(maxFiles, ID_RECENT_FILE_LOWEST)
  , m_FileHistoryList(NULL)
  , m_ProjectHistory(maxProjects, ID_RECENT_PROJECT_LOWEST)
  , m_Process(NULL)
{
  // There is only support for one history in the config.
  // We use file history for this, so update project history ourselves.
  // The order should be inverted, as the last one added is the most recent used.
  if (maxProjects > 0)
  {
    for (int i = maxProjects - 1 ; i >=0 ; i--)
    {
      SetRecentProject(
        wxConfigBase::Get()->Read(wxString::Format("RecentProject%d", i)));
    }
  }

#ifdef wxExUSE_EMBEDDED_SQL
  wxExTool::Get()->AddInfo(
    ID_TOOL_SQL,
    _("Executed %ld SQL queries in"),
    wxExEllipsed(_("&SQL Query Run")));

  wxExTool::Get()->AddInfo(
    ID_TOOL_REPORT_SQL,
    _("Reported %ld SQL queries in"),
    _("Report SQL &Query"));
#endif
}

void wxExFrameWithHistory::DoRecent(
  wxFileHistory& history,
  int index,
  long flags)
{
  if (history.GetCount() > 0)
  {
    const wxString file(history.GetHistoryFile(index));

    if (!wxFileExists(file))
    {
      history.RemoveFileFromHistory(index);
      wxLogMessage(_("Removed not existing file: %s from history"),
        file.c_str());
    }
    else
    {
      OpenFile(file, 0, wxEmptyString, flags);
    }
  }
}

wxExListViewWithFrame* wxExFrameWithHistory::GetProject()
{
  return (wxExListViewWithFrame*)GetFocusedListView();
}

void wxExFrameWithHistory::OnClose(wxCloseEvent& event)
{
  if (event.CanVeto())
  {
    if (ProcessIsRunning())
    {
      wxLogMessage(_("Process is running"));
      event.Veto();
      return;
    }
  }

  wxDELETE(m_Process);

  m_FileHistory.Save(*wxConfigBase::Get());

  for (size_t i = 0; i < m_ProjectHistory.GetCount(); i++)
  {
    wxConfigBase::Get()->Write(
      wxString::Format("RecentProject%d", i),
      m_ProjectHistory.GetHistoryFile(i));
  }

  event.Skip();
}

void wxExFrameWithHistory::OnCommand(wxCommandEvent& event)
{
  if (event.GetId() >= ID_RECENT_FILE_LOWEST &&
      event.GetId() <= ID_RECENT_FILE_HIGHEST)
  {
    DoRecent(m_FileHistory,
      event.GetId() - ID_RECENT_FILE_LOWEST);
  }
  else if (event.GetId() >= ID_RECENT_PROJECT_LOWEST &&
           event.GetId() <= ID_RECENT_PROJECT_HIGHEST)
  {
    DoRecent(m_ProjectHistory,
      event.GetId() - ID_RECENT_PROJECT_LOWEST,
      wxExSTCWithFrame::STC_OPEN_IS_PROJECT);
  }
  else
  {
    switch (event.GetId())
    {
    case wxID_OPEN:
      wxExOpenFilesDialog(this);
      break;

    case wxID_PREFERENCES:
      wxExSTC::ConfigDialog(this,
        _("Editor Options"),
        wxExSTC::STC_CONFIG_MODELESS |
        wxExSTC::STC_CONFIG_SIMPLE |
        wxExSTC::STC_CONFIG_WITH_APPLY,
        event.GetId());
    break;

    case ID_PROJECT_SAVE:
      {
        wxExListViewWithFrame* project = GetProject();
        if (project != NULL)
        {
          project->FileSave();
          SetTitle(wxEmptyString, project->GetFileName().GetName());
        }
      }
      break;

    case ID_SPECIAL_FIND_IN_FILES:
      wxExFindInFiles();
      break;

    case ID_SPECIAL_REPLACE_IN_FILES:
      wxExFindInFiles(false);
      break;

    case ID_TERMINATED_PROCESS:
      wxBell();
      wxDELETE(m_Process);
    break;

    case ID_VIEW_STATUSBAR:
      GetStatusBar()->Show(!GetStatusBar()->IsShown());
      SendSizeEvent();
      break;

    case ID_VIEW_TOOLBAR:
      GetToolBar()->Show(!GetToolBar()->IsShown());
      SendSizeEvent();
      break;

    default:
      wxFAIL;
    }
  }
}

void wxExFrameWithHistory::OnIdle(wxIdleEvent& event)
{
  event.Skip();

  wxWindow* win = wxWindow::FindFocus();
  if (win == NULL) return;

  wxExSTCWithFrame* editor = wxDynamicCast(win, wxExSTCWithFrame);
  wxExListViewWithFrame* project = wxDynamicCast(win, wxExListViewWithFrame);

  const wxString title(GetTitle());
  const wxUniChar indicator('*');

  if ((project != NULL && project->GetContentsChanged()) ||
      (editor != NULL && editor->GetContentsChanged()))
  {
    // Project or editor changed, add indicator if not yet done.
    if (title.Last() != indicator)
    {
      wxFrame::SetTitle(title + " " + indicator);
    }
  }
  else
  {
    // Project or editor not changed, remove indicator if not yet done.
    if (title.Last() == indicator)
    {
      wxFrame::SetTitle(title.substr(0, title.length() - 2));
    }
  }
}

void wxExFrameWithHistory::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
  case ID_VIEW_STATUSBAR:
    wxASSERT(GetStatusBar() != NULL);
    event.Check(GetStatusBar()->IsShown());
    break;

  case ID_VIEW_TOOLBAR:
    wxASSERT(GetToolBar() != NULL) ;
    event.Check(GetToolBar()->IsShown());
    break;

  default:
    wxFAIL;
  }
}

bool wxExFrameWithHistory::OpenFile(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  if (wxExManagedFrame::OpenFile(filename, line_number, match, flags))
  {
    SetRecentFile(filename.GetFullPath());
    return true;
  }

  return false;
}

bool wxExFrameWithHistory::ProcessIsRunning() const
{
  return m_Process != NULL && wxProcess::Exists(m_Process->GetPid());
}

bool wxExFrameWithHistory::ProcessRun(const wxString& command)
{
  wxASSERT(m_Process == NULL);

  wxExListViewWithFrame* listview = Activate(wxExListViewWithFrame::LIST_PROCESS);

  if (listview == NULL)
  {
    wxFAIL;
    return false;
  }

  if ((m_Process = new wxExProcess(listview, command)) != NULL)
  {
    if (m_Process->Execute() <= 0)
    {
      wxDELETE(m_Process);
      return false;
    }
    else
    {
      return true;
    }
  }

  return false;
}

bool wxExFrameWithHistory::ProcessStop()
{
  if (ProcessIsRunning())
  {
    if (m_Process->Kill() == wxKILL_ERROR)
    {
      // Even if the process could not be killed, set it to NULL, as it is deleted.
      wxFAIL;
      m_Process = NULL;
      return false;
    }
    else
    {
      m_Process = NULL;
      return true;
    }
  }

  return true;
}

void wxExFrameWithHistory::SetRecentFile(const wxString& file)
{
  if (!file.empty())
  {
    m_FileHistory.AddFileToHistory(file);

    if (m_FileHistoryList != NULL)
    {
      wxExListItemWithFileName item(m_FileHistoryList, file);
      item.Insert((long)0);

      if (m_FileHistoryList->GetItemCount() > 1)
      {
        for (int i = m_FileHistoryList->GetItemCount() - 1; i >= 1 ; i--)
        {
          wxExListItemWithFileName item(m_FileHistoryList, i);

          if (item.GetFileName().GetFullPath() == file)
          {
            m_FileHistoryList->DeleteItem(i);
          }
        }
      }
    }
  }
}

void wxExFrameWithHistory::SetTitle(
  const wxString& file,
  const wxString& project)
{
  // If one of the strings is empty, try to get a better string.
  wxString better_file(file);
  wxString better_project(project);

  if (better_file.empty())
  {
    wxExSTC* stc = GetSTC();

    if (stc != NULL)
    {
      better_file = stc->GetFileName().GetFullPath();
    }
  }

  if (better_project.empty())
  {
    wxExListViewWithFrame* lv = (wxExListViewWithFrame*)GetListView();

    if (lv != NULL && lv->GetType() == wxExListViewWithFrame::LIST_PROJECT)
    {
      better_project = lv->GetFileName().GetName();
    }
  }

  // And now update the title.
  if (better_file.empty() && better_project.empty())
  {
    wxExFrame::SetTitle(wxTheApp->GetAppName());
  }
  else
  {
    const wxString sep =
      (!better_file.empty() && !better_project.empty() ?
          wxString(" - "):
          wxString(wxEmptyString));

    wxExFrame::SetTitle(better_file + sep + better_project);
  }
}

void wxExFrameWithHistory::UseFileHistory(wxWindowID id, wxMenu* menu)
{
  UseHistory(id, menu, m_FileHistory);

  // We can load file history now.
  m_FileHistory.Load(*wxConfigBase::Get());
}

void wxExFrameWithHistory::UseFileHistoryList(wxExListViewWithFrame* list)
{
  m_FileHistoryList = list;
  m_FileHistoryList->Hide();

  // Add all items from FileHistory.
  for (size_t i = 0; i < m_FileHistory.GetCount(); i++)
  {
    wxExListItemWithFileName item(
      m_FileHistoryList,
      m_FileHistory.GetHistoryFile(i));

    item.Insert();
  }
}

void wxExFrameWithHistory::UseHistory(
  wxWindowID id,
  wxMenu* menu,
  wxFileHistory& history)
{
  wxMenu* submenu = new wxMenu;
  menu->Append(id, _("Open &Recent"), submenu);
  history.UseMenu(submenu);
}

void wxExFrameWithHistory::UseProjectHistory(wxWindowID id, wxMenu* menu)
{
  UseHistory(id, menu, m_ProjectHistory);

  // And add the files to the menu.
  m_ProjectHistory.AddFilesToMenu();
}
<commit_msg>removed unnecessary dependency<commit_after>/******************************************************************************\
* File:          frame.cpp
* Purpose:       Implementation of wxExFrameWithHistory class
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/extension/report/report.h>

BEGIN_EVENT_TABLE(wxExFrameWithHistory, wxExManagedFrame)
  EVT_CLOSE(wxExFrameWithHistory::OnClose)
  EVT_IDLE(wxExFrameWithHistory::OnIdle)
  EVT_MENU(wxID_OPEN, wxExFrameWithHistory::OnCommand)
  EVT_MENU(wxID_PREFERENCES, wxExFrameWithHistory::OnCommand)
  EVT_MENU(ID_TERMINATED_PROCESS, wxExFrameWithHistory::OnCommand)
  EVT_MENU_RANGE(
    ID_EXTENSION_REPORT_LOWEST,
    ID_EXTENSION_REPORT_HIGHEST,
    wxExFrameWithHistory::OnCommand)
  EVT_UPDATE_UI(ID_VIEW_STATUSBAR, wxExFrameWithHistory::OnUpdateUI)
  EVT_UPDATE_UI(ID_VIEW_TOOLBAR, wxExFrameWithHistory::OnUpdateUI)
END_EVENT_TABLE()

wxExFrameWithHistory::wxExFrameWithHistory(wxWindow* parent,
  wxWindowID id,
  const wxString& title,
  size_t maxFiles,
  size_t maxProjects,
  int style)
  : wxExManagedFrame(parent, id, title, style)
  , m_FileHistory(maxFiles, ID_RECENT_FILE_LOWEST)
  , m_FileHistoryList(NULL)
  , m_ProjectHistory(maxProjects, ID_RECENT_PROJECT_LOWEST)
  , m_Process(NULL)
{
  // There is only support for one history in the config.
  // We use file history for this, so update project history ourselves.
  // The order should be inverted, as the last one added is the most recent used.
  if (maxProjects > 0)
  {
    for (int i = maxProjects - 1 ; i >=0 ; i--)
    {
      SetRecentProject(
        wxConfigBase::Get()->Read(wxString::Format("RecentProject%d", i)));
    }
  }

#ifdef wxExUSE_EMBEDDED_SQL
  wxExTool::Get()->AddInfo(
    ID_TOOL_SQL,
    _("Executed %ld SQL queries in"),
    wxExEllipsed(_("&SQL Query Run")));

  wxExTool::Get()->AddInfo(
    ID_TOOL_REPORT_SQL,
    _("Reported %ld SQL queries in"),
    _("Report SQL &Query"));
#endif
}

void wxExFrameWithHistory::DoRecent(
  wxFileHistory& history,
  int index,
  long flags)
{
  if (history.GetCount() > 0)
  {
    const wxString file(history.GetHistoryFile(index));

    if (!wxFileExists(file))
    {
      history.RemoveFileFromHistory(index);
      wxLogMessage(_("Removed not existing file: %s from history"),
        file.c_str());
    }
    else
    {
      OpenFile(file, 0, wxEmptyString, flags);
    }
  }
}

wxExListViewWithFrame* wxExFrameWithHistory::GetProject()
{
  return (wxExListViewWithFrame*)GetFocusedListView();
}

void wxExFrameWithHistory::OnClose(wxCloseEvent& event)
{
  if (event.CanVeto())
  {
    if (ProcessIsRunning())
    {
      wxLogMessage(_("Process is running"));
      event.Veto();
      return;
    }
  }

  wxDELETE(m_Process);

  m_FileHistory.Save(*wxConfigBase::Get());

  for (size_t i = 0; i < m_ProjectHistory.GetCount(); i++)
  {
    wxConfigBase::Get()->Write(
      wxString::Format("RecentProject%d", i),
      m_ProjectHistory.GetHistoryFile(i));
  }

  event.Skip();
}

void wxExFrameWithHistory::OnCommand(wxCommandEvent& event)
{
  if (event.GetId() >= ID_RECENT_FILE_LOWEST &&
      event.GetId() <= ID_RECENT_FILE_HIGHEST)
  {
    DoRecent(m_FileHistory,
      event.GetId() - ID_RECENT_FILE_LOWEST);
  }
  else if (event.GetId() >= ID_RECENT_PROJECT_LOWEST &&
           event.GetId() <= ID_RECENT_PROJECT_HIGHEST)
  {
    DoRecent(m_ProjectHistory,
      event.GetId() - ID_RECENT_PROJECT_LOWEST,
      wxExSTCWithFrame::STC_OPEN_IS_PROJECT);
  }
  else
  {
    switch (event.GetId())
    {
    case wxID_OPEN:
      wxExOpenFilesDialog(this);
      break;

    case wxID_PREFERENCES:
      wxExSTC::ConfigDialog(this,
        _("Editor Options"),
        wxExSTC::STC_CONFIG_MODELESS |
        wxExSTC::STC_CONFIG_SIMPLE |
        wxExSTC::STC_CONFIG_WITH_APPLY,
        event.GetId());
    break;

    case ID_PROJECT_SAVE:
      {
        wxExListViewWithFrame* project = GetProject();
        if (project != NULL)
        {
          project->FileSave();
          SetTitle(wxEmptyString, project->GetFileName().GetName());
        }
      }
      break;

    case ID_SPECIAL_FIND_IN_FILES:
      wxExFindInFiles();
      break;

    case ID_SPECIAL_REPLACE_IN_FILES:
      wxExFindInFiles(false);
      break;

    case ID_TERMINATED_PROCESS:
      wxBell();
      wxDELETE(m_Process);
    break;

    case ID_VIEW_STATUSBAR:
      GetStatusBar()->Show(!GetStatusBar()->IsShown());
      SendSizeEvent();
      break;

    case ID_VIEW_TOOLBAR:
      GetToolBar()->Show(!GetToolBar()->IsShown());
      SendSizeEvent();
      break;

    default:
      wxFAIL;
    }
  }
}

void wxExFrameWithHistory::OnIdle(wxIdleEvent& event)
{
  event.Skip();

  wxWindow* win = wxWindow::FindFocus();
  if (win == NULL) return;

  wxExSTCWithFrame* editor = wxDynamicCast(win, wxExSTCWithFrame);
  wxExListViewWithFrame* project = wxDynamicCast(win, wxExListViewWithFrame);

  const wxString title(GetTitle());
  const wxUniChar indicator('*');

  if ((project != NULL && project->GetContentsChanged()) ||
      (editor != NULL && editor->GetContentsChanged()))
  {
    // Project or editor changed, add indicator if not yet done.
    if (title.Last() != indicator)
    {
      wxFrame::SetTitle(title + " " + indicator);
    }
  }
  else
  {
    // Project or editor not changed, remove indicator if not yet done.
    if (title.Last() == indicator)
    {
      wxFrame::SetTitle(title.substr(0, title.length() - 2));
    }
  }
}

void wxExFrameWithHistory::OnUpdateUI(wxUpdateUIEvent& event)
{
  switch (event.GetId())
  {
  case ID_VIEW_STATUSBAR:
    wxASSERT(GetStatusBar() != NULL);
    event.Check(GetStatusBar()->IsShown());
    break;

  case ID_VIEW_TOOLBAR:
    wxASSERT(GetToolBar() != NULL) ;
    event.Check(GetToolBar()->IsShown());
    break;

  default:
    wxFAIL;
  }
}

bool wxExFrameWithHistory::OpenFile(
  const wxExFileName& filename,
  int line_number,
  const wxString& match,
  long flags)
{
  if (wxExManagedFrame::OpenFile(filename, line_number, match, flags))
  {
    SetRecentFile(filename.GetFullPath());
    return true;
  }

  return false;
}

bool wxExFrameWithHistory::ProcessIsRunning() const
{
  return m_Process != NULL && wxProcess::Exists(m_Process->GetPid());
}

bool wxExFrameWithHistory::ProcessRun(const wxString& command)
{
  wxASSERT(m_Process == NULL);

  wxExListViewWithFrame* listview = Activate(wxExListViewWithFrame::LIST_PROCESS);

  if (listview == NULL)
  {
    wxFAIL;
    return false;
  }

  if ((m_Process = new wxExProcess(listview, command)) != NULL)
  {
    if (m_Process->Execute() <= 0)
    {
      wxDELETE(m_Process);
      return false;
    }
    else
    {
      return true;
    }
  }

  return false;
}

bool wxExFrameWithHistory::ProcessStop()
{
  if (ProcessIsRunning())
  {
    if (m_Process->Kill() == wxKILL_ERROR)
    {
      // Even if the process could not be killed, set it to NULL, as it is deleted.
      wxFAIL;
      m_Process = NULL;
      return false;
    }
    else
    {
      m_Process = NULL;
      return true;
    }
  }

  return true;
}

void wxExFrameWithHistory::SetRecentFile(const wxString& file)
{
  if (!file.empty())
  {
    m_FileHistory.AddFileToHistory(file);

    if (m_FileHistoryList != NULL)
    {
      wxExListItemWithFileName item(m_FileHistoryList, file);
      item.Insert((long)0);

      if (m_FileHistoryList->GetItemCount() > 1)
      {
        for (int i = m_FileHistoryList->GetItemCount() - 1; i >= 1 ; i--)
        {
          wxExListItemWithFileName item(m_FileHistoryList, i);

          if (item.GetFileName().GetFullPath() == file)
          {
            m_FileHistoryList->DeleteItem(i);
          }
        }
      }
    }
  }
}

void wxExFrameWithHistory::SetTitle(
  const wxString& file,
  const wxString& project)
{
  // If one of the strings is empty, try to get a better string.
  wxString better_file(file);
  wxString better_project(project);

  if (better_file.empty())
  {
    wxExSTC* stc = GetSTC();

    if (stc != NULL)
    {
      better_file = stc->GetFileName().GetFullPath();
    }
  }

  if (better_project.empty())
  {
    wxExListViewWithFrame* lv = (wxExListViewWithFrame*)GetListView();

    if (lv != NULL && lv->GetType() == wxExListViewWithFrame::LIST_PROJECT)
    {
      better_project = lv->GetFileName().GetName();
    }
  }

  // And now update the title.
  if (better_file.empty() && better_project.empty())
  {
    wxExFrame::SetTitle(wxTheApp->GetAppName());
  }
  else
  {
    const wxString sep =
      (!better_file.empty() && !better_project.empty() ?
          wxString(" - "):
          wxString(wxEmptyString));

    wxExFrame::SetTitle(better_file + sep + better_project);
  }
}

void wxExFrameWithHistory::UseFileHistory(wxWindowID id, wxMenu* menu)
{
  UseHistory(id, menu, m_FileHistory);

  // We can load file history now.
  m_FileHistory.Load(*wxConfigBase::Get());
}

void wxExFrameWithHistory::UseFileHistoryList(wxExListViewWithFrame* list)
{
  m_FileHistoryList = list;
  m_FileHistoryList->Hide();

  // Add all items from FileHistory.
  for (size_t i = 0; i < m_FileHistory.GetCount(); i++)
  {
    wxExListItemWithFileName item(
      m_FileHistoryList,
      m_FileHistory.GetHistoryFile(i));

    item.Insert();
  }
}

void wxExFrameWithHistory::UseHistory(
  wxWindowID id,
  wxMenu* menu,
  wxFileHistory& history)
{
  wxMenu* submenu = new wxMenu;
  menu->Append(id, _("Open &Recent"), submenu);
  history.UseMenu(submenu);
}

void wxExFrameWithHistory::UseProjectHistory(wxWindowID id, wxMenu* menu)
{
  UseHistory(id, menu, m_ProjectHistory);

  // And add the files to the menu.
  m_ProjectHistory.AddFilesToMenu();
}
<|endoftext|>


<commit_before>#include "npapi-headers/npapi.h"
<commit_msg>Start implementing the relevant hooks<commit_after>#define XP_UNIX 1
#include "npapi-headers/npapi.h"
#include "npapi-headers/npfunctions.h"

NP_EXPORT(NPError) OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
    pFuncs->size = sizeof(*pFuncs);
    pFuncs->version = 0; // My version?
    // TODO: implement the functions I need.
    return NPERR_NO_ERROR;
}

NP_EXPORT(NPError) OSCALL NP_Initialize(NPNetscapeFuncs* bFuncs,
					NPPluginFuncs* pFuncs)
{
    NPError err;

    // TODO: save bFuncs

    // On Unix, it looks like NP_GetEntryPoints isn't called directly?
    // The prototype for NP_Initialize is different from everyone
    // else. Meh.
    return NP_GetEntryPoints(pFuncs);
}
<|endoftext|>


<commit_before>/************************************************
 * Copyright (c) IBM Corp. 2014-2015
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *************************************************/

/*
 * skv_server_lock_manager.hpp
 *
 *  Created on: May 5, 2015
 *      Author: lschneid
 */

#ifndef SKV_SERVER_SKV_SERVER_LOCK_MANAGER_HPP_
#define SKV_SERVER_SKV_SERVER_LOCK_MANAGER_HPP_

#ifndef SKV_SERVER_RECORD_LOCK_MGR_LOG
#define SKV_SERVER_RECORD_LOCK_MGR_LOG ( 0 | SKV_LOGGING_ALL )
#endif

#include <set>

class skv_server_record_lock_key_t
{
  skv_pds_id_t mPDSId;
  skv_key_t mKey;
  char mKeyData[ SKV_CONTROL_MESSAGE_SIZE ];

public:
  skv_server_record_lock_key_t()
  {
    mPDSId.Init( 0, 0 );
    mKey.Init( NULL, 0 );
    mKey.mData = mKeyData;
  }
  skv_server_record_lock_key_t( const skv_server_record_lock_key_t &aLockRec )
  {
    setPdsId( aLockRec.mPDSId );
    mKey.mData = mKeyData;
    setKey( aLockRec.mKey );
  }
  skv_server_record_lock_key_t( const skv_pds_id_t &aPDSId,
                                const skv_key_t &aKey )
  {
    setPdsId( aPDSId );
    mKey.mData = mKeyData;
    setKey( aKey );
  }
  ~skv_server_record_lock_key_t()
  {
  }

  const skv_key_t& getKey() const
  {
    return mKey;
  }

  void setKey( const skv_key_value_in_ctrl_msg_t &aKeyVal )
  {
    mKey.mData = mKeyData;
    mKey.mSizeBE = htonl( aKeyVal.mKeySize );
    if( mKey.mSize() < SKV_CONTROL_MESSAGE_SIZE )
      memcpy( mKey.mData, aKeyVal.mData, mKey.mSize() );
    else
      StrongAssertLogLine( 0 )
        << "KeySize too large (check client request or potential endian issue)."
        << " size=" << mKey.mSize()
        << " in hex=0x" << (void*)mKey.mSize()
        << EndLogLine;
  }
  void setKey( const skv_key_t& aKey )
  {
    mKey.mSizeBE = aKey.mSizeBE;
    mKey.mData = mKeyData;
    memcpy( mKeyData, aKey.mData, mKey.mSize() );
  }

  skv_pds_id_t getPdsId() const
  {
    return mPDSId;
  }

  void setPdsId( const skv_pds_id_t &aPDSId )
  {
    mPDSId.Init( aPDSId.mOwnerNodeId, aPDSId.mIdOnOwner );
  }

  skv_server_record_lock_key_t&
  operator=( const skv_server_record_lock_key_t &aLockRec )
  {
    setPdsId( aLockRec.mPDSId );
    mKey.mData = mKeyData;
    memcpy( mKeyData, aLockRec.mKeyData, mKey.mSize() );
    setKey( aLockRec.mKey );

    return *this;
  }

  bool
  operator==( const skv_server_record_lock_key_t &aLockRec ) const
  {
    if( (aLockRec.mPDSId == mPDSId) )
      return (mKey == aLockRec.mKey);
    else
      return 0;
  }

  bool
  operator<( const skv_server_record_lock_key_t &aLockRec ) const
  {
    if( mPDSId < aLockRec.mPDSId )
    {
      return 1;
    }
    else if( mPDSId == aLockRec.mPDSId )
    {
      int rc = (mKey < aLockRec.mKey);

      return rc;
    }
    else
    {
      return 0;
    }
  }

};

struct skv_server_record_lock_t
{
  skv_server_record_lock_key_t mKey;
  skv_server_ccb_t *mLockOwner;
};

// once there's a decision to accept C++11 features by default, this could be changed to an unordered map
typedef std::map< skv_server_record_lock_key_t,
                  skv_server_ccb_t*,
                  less< skv_server_record_lock_key_t >,
                  skv_allocator_t< std::pair< skv_server_record_lock_key_t, skv_server_record_lock_t* >> > skv_server_record_lock_vault_t;;

class skv_server_lock_manager_t
{
  skv_server_record_lock_vault_t mActiveLocks;
  skv_server_record_lock_t mTmpRecord;
  skv_mutex_t mSerializer;

public:
  skv_server_lock_manager_t()
  {
  }
  ~skv_server_lock_manager_t()
  {
  }

  skv_status_t Lock( const skv_pds_id_t *aPDSId,
                     const skv_key_value_in_ctrl_msg_t *aKeyValue,
                     const skv_server_ccb_t *aOwner,
                     skv_rec_lock_handle_t *aRecLock )
  {
    skv_status_t status = SKV_SUCCESS;
    mTmpRecord.mKey.setPdsId( *aPDSId );
    mTmpRecord.mKey.setKey( *aKeyValue );

    // note: operator[] inserts new element if key isn't found...
    skv_server_record_lock_vault_t::iterator iter = mActiveLocks.find( mTmpRecord.mKey );

    if( iter != mActiveLocks.end() )
    {
      skv_server_ccb_t *currentOwner = iter->second;
      if( currentOwner != aOwner )
      {
        BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
          << "This record is already locked and we 0x" << (void*)aOwner
          << " are NOT the owner 0x" << (void*)currentOwner
          << EndLogLine;
        status = SKV_ERRNO_RECORD_IS_LOCKED;
      }
      else
      {
        BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
          << "This record is already locked and we're the owner 0x" << (void*)aOwner
          << EndLogLine;
        *aRecLock = (skv_rec_lock_handle_t)&(iter->first);
        status = SKV_SUCCESS;
      }
    }
    else
    {
      BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
        << "This record didn't exist. Creating record lock for owner 0x" << (void*)aOwner
        << EndLogLine;
      std::pair<skv_server_record_lock_vault_t::iterator,bool> retval = mActiveLocks.insert( std::make_pair( mTmpRecord.mKey, (skv_server_ccb_t*)aOwner ) );
      if( retval.second == true )
      {
        *aRecLock = (skv_rec_lock_handle_t)&(retval.first->first);
        status = SKV_SUCCESS;
      }
      else
        StrongAssertLogLine( 0 )
          << "Lock creation failed while inserting key into map. Sorry, can't continue..."
          << EndLogLine;
    }

    return status;
  }

  skv_status_t Unlock( const skv_rec_lock_handle_t aLock,
                       const skv_server_ccb_t *aOwner )
  {
    skv_status_t status = SKV_SUCCESS;
    skv_server_record_lock_key_t *lockPtr = (skv_server_record_lock_key_t*)aLock;
    skv_server_record_lock_vault_t::iterator iter = mActiveLocks.find( *lockPtr );
    if( iter != mActiveLocks.end() )
      if( iter->second == aOwner )
      {
        BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
          << "This record is locked and we're the owner 0x" << (void*)aOwner
          << ". Unlocking..."
          << EndLogLine;
        mActiveLocks.erase( *lockPtr );
        status = SKV_SUCCESS;
      }
      else
      {
        BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
          << "This record is locked and we 0x" << (void*)aOwner
          << " are NOT the owner 0x" << (void*)iter->second
          << ". Nice try..."
          << EndLogLine;
        status = SKV_ERRNO_RECORD_IS_LOCKED;
      }
    else
    {
      BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
        << "This record isn't locked. No-Op."
        << EndLogLine;
      status = SKV_SUCCESS;
    }

    return status;
  }
};

#endif /* SKV_SERVER_SKV_SERVER_LOCK_MANAGER_HPP_ */
<commit_msg>fix: use std allocator for locking to enable lock functionality for rocksdb LKVS<commit_after>/************************************************
 * Copyright (c) IBM Corp. 2014-2015
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *************************************************/

/*
 * skv_server_lock_manager.hpp
 *
 *  Created on: May 5, 2015
 *      Author: lschneid
 */

#ifndef SKV_SERVER_SKV_SERVER_LOCK_MANAGER_HPP_
#define SKV_SERVER_SKV_SERVER_LOCK_MANAGER_HPP_

#ifndef SKV_SERVER_RECORD_LOCK_MGR_LOG
#define SKV_SERVER_RECORD_LOCK_MGR_LOG ( 0 | SKV_LOGGING_ALL )
#endif

#include <set>

class skv_server_record_lock_key_t
{
  skv_pds_id_t mPDSId;
  skv_key_t mKey;
  char mKeyData[ SKV_CONTROL_MESSAGE_SIZE ];

public:
  skv_server_record_lock_key_t()
  {
    mPDSId.Init( 0, 0 );
    mKey.Init( NULL, 0 );
    mKey.mData = mKeyData;
  }
  skv_server_record_lock_key_t( const skv_server_record_lock_key_t &aLockRec )
  {
    setPdsId( aLockRec.mPDSId );
    mKey.mData = mKeyData;
    setKey( aLockRec.mKey );
  }
  skv_server_record_lock_key_t( const skv_pds_id_t &aPDSId,
                                const skv_key_t &aKey )
  {
    setPdsId( aPDSId );
    mKey.mData = mKeyData;
    setKey( aKey );
  }
  ~skv_server_record_lock_key_t()
  {
  }

  const skv_key_t& getKey() const
  {
    return mKey;
  }

  void setKey( const skv_key_value_in_ctrl_msg_t &aKeyVal )
  {
    mKey.mData = mKeyData;
    mKey.mSizeBE = htonl( aKeyVal.mKeySize );
    if( mKey.mSize() < SKV_CONTROL_MESSAGE_SIZE )
      memcpy( mKey.mData, aKeyVal.mData, mKey.mSize() );
    else
      StrongAssertLogLine( 0 )
        << "KeySize too large (check client request or potential endian issue)."
        << " size=" << mKey.mSize()
        << " in hex=0x" << (void*)mKey.mSize()
        << EndLogLine;
  }
  void setKey( const skv_key_t& aKey )
  {
    mKey.mSizeBE = aKey.mSizeBE;
    mKey.mData = mKeyData;
    memcpy( mKeyData, aKey.mData, mKey.mSize() );
  }

  skv_pds_id_t getPdsId() const
  {
    return mPDSId;
  }

  void setPdsId( const skv_pds_id_t &aPDSId )
  {
    mPDSId.Init( aPDSId.mOwnerNodeId, aPDSId.mIdOnOwner );
  }

  skv_server_record_lock_key_t&
  operator=( const skv_server_record_lock_key_t &aLockRec )
  {
    setPdsId( aLockRec.mPDSId );
    mKey.mData = mKeyData;
    memcpy( mKeyData, aLockRec.mKeyData, mKey.mSize() );
    setKey( aLockRec.mKey );

    return *this;
  }

  bool
  operator==( const skv_server_record_lock_key_t &aLockRec ) const
  {
    if( (aLockRec.mPDSId == mPDSId) )
      return (mKey == aLockRec.mKey);
    else
      return 0;
  }

  bool
  operator<( const skv_server_record_lock_key_t &aLockRec ) const
  {
    if( mPDSId < aLockRec.mPDSId )
    {
      return 1;
    }
    else if( mPDSId == aLockRec.mPDSId )
    {
      int rc = (mKey < aLockRec.mKey);

      return rc;
    }
    else
    {
      return 0;
    }
  }

};

struct skv_server_record_lock_t
{
  skv_server_record_lock_key_t mKey;
  skv_server_ccb_t *mLockOwner;
};

// once there's a decision to accept C++11 features by default, this could be changed to an unordered map
typedef std::map< skv_server_record_lock_key_t,
                  skv_server_ccb_t*,
                  less< skv_server_record_lock_key_t > > skv_server_record_lock_vault_t;

class skv_server_lock_manager_t
{
  skv_server_record_lock_vault_t mActiveLocks;
  skv_server_record_lock_t mTmpRecord;
  skv_mutex_t mSerializer;

public:
  skv_server_lock_manager_t()
  {
  }
  ~skv_server_lock_manager_t()
  {
  }

  skv_status_t Lock( const skv_pds_id_t *aPDSId,
                     const skv_key_value_in_ctrl_msg_t *aKeyValue,
                     const skv_server_ccb_t *aOwner,
                     skv_rec_lock_handle_t *aRecLock )
  {
    skv_status_t status = SKV_SUCCESS;
    mTmpRecord.mKey.setPdsId( *aPDSId );
    mTmpRecord.mKey.setKey( *aKeyValue );

    // note: operator[] inserts new element if key isn't found...
    skv_server_record_lock_vault_t::iterator iter = mActiveLocks.find( mTmpRecord.mKey );

    if( iter != mActiveLocks.end() )
    {
      skv_server_ccb_t *currentOwner = iter->second;
      if( currentOwner != aOwner )
      {
        BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
          << "This record is already locked and we 0x" << (void*)aOwner
          << " are NOT the owner 0x" << (void*)currentOwner
          << EndLogLine;
        status = SKV_ERRNO_RECORD_IS_LOCKED;
      }
      else
      {
        BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
          << "This record is already locked and we're the owner 0x" << (void*)aOwner
          << EndLogLine;
        *aRecLock = (skv_rec_lock_handle_t)&(iter->first);
        status = SKV_SUCCESS;
      }
    }
    else
    {
      BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
        << "This record didn't exist. Creating record lock for owner 0x" << (void*)aOwner
        << EndLogLine;
      std::pair<skv_server_record_lock_vault_t::iterator,bool> retval = mActiveLocks.insert( std::make_pair( mTmpRecord.mKey, (skv_server_ccb_t*)aOwner ) );
      if( retval.second == true )
      {
        *aRecLock = (skv_rec_lock_handle_t)&(retval.first->first);
        status = SKV_SUCCESS;
      }
      else
        StrongAssertLogLine( 0 )
          << "Lock creation failed while inserting key into map. Sorry, can't continue..."
          << EndLogLine;
    }

    return status;
  }

  skv_status_t Unlock( const skv_rec_lock_handle_t aLock,
                       const skv_server_ccb_t *aOwner )
  {
    skv_status_t status = SKV_SUCCESS;
    skv_server_record_lock_key_t *lockPtr = (skv_server_record_lock_key_t*)aLock;
    skv_server_record_lock_vault_t::iterator iter = mActiveLocks.find( *lockPtr );
    if( iter != mActiveLocks.end() )
      if( iter->second == aOwner )
      {
        BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
          << "This record is locked and we're the owner 0x" << (void*)aOwner
          << ". Unlocking..."
          << EndLogLine;
        mActiveLocks.erase( *lockPtr );
        status = SKV_SUCCESS;
      }
      else
      {
        BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
          << "This record is locked and we 0x" << (void*)aOwner
          << " are NOT the owner 0x" << (void*)iter->second
          << ". Nice try..."
          << EndLogLine;
        status = SKV_ERRNO_RECORD_IS_LOCKED;
      }
    else
    {
      BegLogLine( SKV_SERVER_RECORD_LOCK_MGR_LOG )
        << "This record isn't locked. No-Op."
        << EndLogLine;
      status = SKV_SUCCESS;
    }

    return status;
  }
};

#endif /* SKV_SERVER_SKV_SERVER_LOCK_MANAGER_HPP_ */
<|endoftext|>