<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: uiitems.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:49:33 $
 *
 *  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 _SVX_ITEMTYPE_HXX
#include <svx/itemtype.hxx>
#endif
#ifndef _UNOSETT_HXX
#include <unosett.hxx>
#endif

#include "swtypes.hxx"
#include "cmdid.h"
#include "pagedesc.hxx"
#include "uiitems.hxx"

#include "utlui.hrc"
#include "attrdesc.hrc"
#ifndef _UNOMID_H
#include <unomid.h>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

// Breitenangaben der Fussnotenlinien, mit TabPage abstimmen
static const USHORT __FAR_DATA nFtnLines[] = {
    0,
    10,
    50,
    80,
    100,
    150
};

#define FTN_LINE_STYLE_COUNT 5

SwPageFtnInfoItem::SwPageFtnInfoItem( const USHORT nId, SwPageFtnInfo& rInfo) :
    SfxPoolItem( nId ),
    aFtnInfo(rInfo)
{
}

SwPageFtnInfoItem::SwPageFtnInfoItem( const SwPageFtnInfoItem& rItem ) :
    SfxPoolItem( rItem ),
    aFtnInfo(rItem.GetPageFtnInfo())
{
}

 SwPageFtnInfoItem::~SwPageFtnInfoItem()
{
}

SfxPoolItem*  SwPageFtnInfoItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SwPageFtnInfoItem( *this );
}

int  SwPageFtnInfoItem::operator==( const SfxPoolItem& rAttr ) const
{
    DBG_ASSERT( Which() == rAttr.Which(), "keine gleichen Attribute" );
    return ( aFtnInfo == ((SwPageFtnInfoItem&)rAttr).GetPageFtnInfo());
}

SfxItemPresentation  SwPageFtnInfoItem::GetPresentation
(
    SfxItemPresentation ePres,
    SfxMapUnit          eCoreUnit,
    SfxMapUnit          ePresUnit,
    String&             rText,
    const IntlWrapper*    pIntl
)   const
{
    switch ( ePres )
    {
        case SFX_ITEM_PRESENTATION_NONE:
            rText.Erase();
            return SFX_ITEM_PRESENTATION_NONE;
        case SFX_ITEM_PRESENTATION_NAMELESS:
        case SFX_ITEM_PRESENTATION_COMPLETE:
        {
            USHORT nHght = (USHORT) GetPageFtnInfo().GetHeight();
            if ( nHght )
            {
                rText = SW_RESSTR( STR_MAX_FTN_HEIGHT );
                rText += ' ';
                rText += ::GetMetricText( nHght, eCoreUnit, ePresUnit, pIntl );
                rText += ::GetSvxString( ::GetMetricId( ePresUnit ) );
            }
            return ePres;
        }
        default:; //prevent warning
    }
    return SFX_ITEM_PRESENTATION_NONE;
}
/* -----------------------------26.04.01 12:25--------------------------------

 ---------------------------------------------------------------------------*/
BOOL SwPageFtnInfoItem::QueryValue( Any& rVal, BYTE nMemberId ) const
{
    sal_Bool bRet = sal_True;
    switch(nMemberId & ~CONVERT_TWIPS)
    {
        case MID_FTN_HEIGHT        :     rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetHeight());break;
        case MID_LINE_WEIGHT       :     rVal <<= (sal_Int16)TWIP_TO_MM100_UNSIGNED(aFtnInfo.GetLineWidth());break;
        case MID_LINE_COLOR        :     rVal <<= (sal_Int32)aFtnInfo.GetLineColor().GetColor();break;
        case MID_LINE_RELWIDTH     :
        {
            Fraction aTmp( 100, 1 );
            aTmp *= aFtnInfo.GetWidth();
            rVal <<= (sal_Int8)(long)aTmp;
        }
        break;
        case MID_LINE_ADJUST       :     rVal <<= (sal_Int16)aFtnInfo.GetAdj();break;//text::HorizontalAdjust
        case MID_LINE_TEXT_DIST    :     rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetTopDist());break;
        case MID_LINE_FOOTNOTE_DIST:     rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetBottomDist());break;
        default:
            bRet = sal_False;
    }
    return bRet;
}
/* -----------------------------26.04.01 12:26--------------------------------

 ---------------------------------------------------------------------------*/
BOOL SwPageFtnInfoItem::PutValue(const Any& rVal, BYTE nMemberId)
{
    sal_Int32 nSet32;
    sal_Bool bRet = sal_True;
    switch(nMemberId  & ~CONVERT_TWIPS)
    {
        case MID_LINE_COLOR        :
            rVal >>= nSet32;
            aFtnInfo.SetLineColor(nSet32);
        break;
        case MID_FTN_HEIGHT:
        case MID_LINE_TEXT_DIST    :
        case MID_LINE_FOOTNOTE_DIST:
                rVal >>= nSet32;
                if(nSet32 < 0)
                    bRet = sal_False;
                else
                {
                    nSet32 = MM100_TO_TWIP(nSet32);
                    switch(nMemberId & ~CONVERT_TWIPS)
                    {
                        case MID_FTN_HEIGHT:            aFtnInfo.SetHeight(nSet32);    break;
                        case MID_LINE_TEXT_DIST:        aFtnInfo.SetTopDist(nSet32);break;
                        case MID_LINE_FOOTNOTE_DIST:    aFtnInfo.SetBottomDist(nSet32);break;
                    }
                }
        break;
        case MID_LINE_WEIGHT       :
        {
            sal_Int16 nSet; rVal >>= nSet;
            if(nSet >= 0)
                aFtnInfo.SetLineWidth(MM100_TO_TWIP(nSet));
            else
                bRet = sal_False;
        }
        break;
        case MID_LINE_RELWIDTH     :
        {
            sal_Int8 nSet; rVal >>= nSet;
            if(nSet < 0)
                bRet = sal_False;
            else
                aFtnInfo.SetWidth(Fraction(nSet, 100));
        }
        break;
        case MID_LINE_ADJUST       :
        {
            sal_Int16 nSet; rVal >>= nSet;
            if(nSet >= 0 && nSet < 3) //text::HorizontalAdjust
                aFtnInfo.SetAdj((SwFtnAdj)nSet);
            else
                bRet = sal_False;
        }
        break;
        default:
            bRet = sal_False;
    }
    return bRet;
}

SwPtrItem::SwPtrItem( const USHORT nId, void* pPtr ) :
    SfxPoolItem( nId ),
    pMisc(pPtr)
{
}

/*--------------------------------------------------------------------
    Beschreibung: Copy-Konstruktor
 --------------------------------------------------------------------*/

SwPtrItem::SwPtrItem( const SwPtrItem& rItem ) : SfxPoolItem( rItem )
{
    pMisc = rItem.pMisc;
}

/*--------------------------------------------------------------------
    Beschreibung: Clonen
 --------------------------------------------------------------------*/

SfxPoolItem* SwPtrItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SwPtrItem( *this );
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

int SwPtrItem::operator==( const SfxPoolItem& rAttr ) const
{
    DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
    const SwPtrItem& rItem = (SwPtrItem&)rAttr;
    return ( pMisc == rItem.pMisc );
}

/*-----------------12.11.97 12:55-------------------------------
 SwUINumRuleItem fuer die NumTabPages der FormatNumRule/Stylisten
---------------------------------------------------------------*/
SwUINumRuleItem::SwUINumRuleItem( const SwNumRule& rRul, const USHORT nId )
    : SfxPoolItem( nId ), pRule( new SwNumRule( rRul ) )
{
}

SwUINumRuleItem::SwUINumRuleItem( const SwUINumRuleItem& rItem )
    : SfxPoolItem( rItem ),
    pRule( new SwNumRule( *rItem.pRule ))
{
}

 SwUINumRuleItem::~SwUINumRuleItem()
{
    delete pRule;
}

SfxPoolItem*  SwUINumRuleItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SwUINumRuleItem( *this );
}

int  SwUINumRuleItem::operator==( const SfxPoolItem& rAttr ) const
{
    DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
    return *pRule == *((SwUINumRuleItem&)rAttr).pRule;
}

BOOL SwUINumRuleItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
    uno::Reference< container::XIndexReplace >xRules = new SwXNumberingRules(*pRule);
    rVal.setValue(&xRules, ::getCppuType((uno::Reference< container::XIndexReplace>*)0));
    return TRUE;
}
BOOL SwUINumRuleItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
    uno::Reference< container::XIndexReplace> xRulesRef;
    if(rVal >>= xRulesRef)
    {
        uno::Reference< lang::XUnoTunnel > xTunnel(xRulesRef, uno::UNO_QUERY);
        SwXNumberingRules* pSwXRules = xTunnel.is() ? reinterpret_cast<SwXNumberingRules*>(
                    xTunnel->getSomething(SwXNumberingRules::getUnoTunnelId())) : 0;
        if(pSwXRules)
        {
            *pRule = *pSwXRules->GetNumRule();
        }
    }
    return TRUE;
}
/* -----------------17.06.98 17:43-------------------
 *
 * --------------------------------------------------*/
SwBackgroundDestinationItem::SwBackgroundDestinationItem(USHORT  _nWhich, USHORT nValue) :
    SfxUInt16Item(_nWhich, nValue)
{
}
/* -----------------17.06.98 17:44-------------------
 *
 * --------------------------------------------------*/
SfxPoolItem*     SwBackgroundDestinationItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SwBackgroundDestinationItem(Which(), GetValue());
}

<commit_msg>INTEGRATION: CWS pj86 (1.11.4); FILE MERGED 2007/09/28 21:36:50 pjanik 1.11.4.1: #i81574#: Initialize variable(s) to prevent warnings on Mac OS X with gcc-4.0.1.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: uiitems.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2007-11-12 16:33:40 $
 *
 *  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 _SVX_ITEMTYPE_HXX
#include <svx/itemtype.hxx>
#endif
#ifndef _UNOSETT_HXX
#include <unosett.hxx>
#endif

#include "swtypes.hxx"
#include "cmdid.h"
#include "pagedesc.hxx"
#include "uiitems.hxx"

#include "utlui.hrc"
#include "attrdesc.hrc"
#ifndef _UNOMID_H
#include <unomid.h>
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;

// Breitenangaben der Fussnotenlinien, mit TabPage abstimmen
static const USHORT __FAR_DATA nFtnLines[] = {
    0,
    10,
    50,
    80,
    100,
    150
};

#define FTN_LINE_STYLE_COUNT 5

SwPageFtnInfoItem::SwPageFtnInfoItem( const USHORT nId, SwPageFtnInfo& rInfo) :
    SfxPoolItem( nId ),
    aFtnInfo(rInfo)
{
}

SwPageFtnInfoItem::SwPageFtnInfoItem( const SwPageFtnInfoItem& rItem ) :
    SfxPoolItem( rItem ),
    aFtnInfo(rItem.GetPageFtnInfo())
{
}

 SwPageFtnInfoItem::~SwPageFtnInfoItem()
{
}

SfxPoolItem*  SwPageFtnInfoItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SwPageFtnInfoItem( *this );
}

int  SwPageFtnInfoItem::operator==( const SfxPoolItem& rAttr ) const
{
    DBG_ASSERT( Which() == rAttr.Which(), "keine gleichen Attribute" );
    return ( aFtnInfo == ((SwPageFtnInfoItem&)rAttr).GetPageFtnInfo());
}

SfxItemPresentation  SwPageFtnInfoItem::GetPresentation
(
    SfxItemPresentation ePres,
    SfxMapUnit          eCoreUnit,
    SfxMapUnit          ePresUnit,
    String&             rText,
    const IntlWrapper*    pIntl
)   const
{
    switch ( ePres )
    {
        case SFX_ITEM_PRESENTATION_NONE:
            rText.Erase();
            return SFX_ITEM_PRESENTATION_NONE;
        case SFX_ITEM_PRESENTATION_NAMELESS:
        case SFX_ITEM_PRESENTATION_COMPLETE:
        {
            USHORT nHght = (USHORT) GetPageFtnInfo().GetHeight();
            if ( nHght )
            {
                rText = SW_RESSTR( STR_MAX_FTN_HEIGHT );
                rText += ' ';
                rText += ::GetMetricText( nHght, eCoreUnit, ePresUnit, pIntl );
                rText += ::GetSvxString( ::GetMetricId( ePresUnit ) );
            }
            return ePres;
        }
        default:; //prevent warning
    }
    return SFX_ITEM_PRESENTATION_NONE;
}
/* -----------------------------26.04.01 12:25--------------------------------

 ---------------------------------------------------------------------------*/
BOOL SwPageFtnInfoItem::QueryValue( Any& rVal, BYTE nMemberId ) const
{
    sal_Bool bRet = sal_True;
    switch(nMemberId & ~CONVERT_TWIPS)
    {
        case MID_FTN_HEIGHT        :     rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetHeight());break;
        case MID_LINE_WEIGHT       :     rVal <<= (sal_Int16)TWIP_TO_MM100_UNSIGNED(aFtnInfo.GetLineWidth());break;
        case MID_LINE_COLOR        :     rVal <<= (sal_Int32)aFtnInfo.GetLineColor().GetColor();break;
        case MID_LINE_RELWIDTH     :
        {
            Fraction aTmp( 100, 1 );
            aTmp *= aFtnInfo.GetWidth();
            rVal <<= (sal_Int8)(long)aTmp;
        }
        break;
        case MID_LINE_ADJUST       :     rVal <<= (sal_Int16)aFtnInfo.GetAdj();break;//text::HorizontalAdjust
        case MID_LINE_TEXT_DIST    :     rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetTopDist());break;
        case MID_LINE_FOOTNOTE_DIST:     rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetBottomDist());break;
        default:
            bRet = sal_False;
    }
    return bRet;
}
/* -----------------------------26.04.01 12:26--------------------------------

 ---------------------------------------------------------------------------*/
BOOL SwPageFtnInfoItem::PutValue(const Any& rVal, BYTE nMemberId)
{
    sal_Int32 nSet32 = 0;
    sal_Bool bRet = sal_True;
    switch(nMemberId  & ~CONVERT_TWIPS)
    {
        case MID_LINE_COLOR        :
            rVal >>= nSet32;
            aFtnInfo.SetLineColor(nSet32);
        break;
        case MID_FTN_HEIGHT:
        case MID_LINE_TEXT_DIST    :
        case MID_LINE_FOOTNOTE_DIST:
                rVal >>= nSet32;
                if(nSet32 < 0)
                    bRet = sal_False;
                else
                {
                    nSet32 = MM100_TO_TWIP(nSet32);
                    switch(nMemberId & ~CONVERT_TWIPS)
                    {
                        case MID_FTN_HEIGHT:            aFtnInfo.SetHeight(nSet32);    break;
                        case MID_LINE_TEXT_DIST:        aFtnInfo.SetTopDist(nSet32);break;
                        case MID_LINE_FOOTNOTE_DIST:    aFtnInfo.SetBottomDist(nSet32);break;
                    }
                }
        break;
        case MID_LINE_WEIGHT       :
        {
            sal_Int16 nSet = 0;
            rVal >>= nSet;
            if(nSet >= 0)
                aFtnInfo.SetLineWidth(MM100_TO_TWIP(nSet));
            else
                bRet = sal_False;
        }
        break;
        case MID_LINE_RELWIDTH     :
        {
            sal_Int8 nSet = 0;
            rVal >>= nSet;
            if(nSet < 0)
                bRet = sal_False;
            else
                aFtnInfo.SetWidth(Fraction(nSet, 100));
        }
        break;
        case MID_LINE_ADJUST       :
        {
            sal_Int16 nSet = 0;
            rVal >>= nSet;
            if(nSet >= 0 && nSet < 3) //text::HorizontalAdjust
                aFtnInfo.SetAdj((SwFtnAdj)nSet);
            else
                bRet = sal_False;
        }
        break;
        default:
            bRet = sal_False;
    }
    return bRet;
}

SwPtrItem::SwPtrItem( const USHORT nId, void* pPtr ) :
    SfxPoolItem( nId ),
    pMisc(pPtr)
{
}

/*--------------------------------------------------------------------
    Beschreibung: Copy-Konstruktor
 --------------------------------------------------------------------*/

SwPtrItem::SwPtrItem( const SwPtrItem& rItem ) : SfxPoolItem( rItem )
{
    pMisc = rItem.pMisc;
}

/*--------------------------------------------------------------------
    Beschreibung: Clonen
 --------------------------------------------------------------------*/

SfxPoolItem* SwPtrItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SwPtrItem( *this );
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

int SwPtrItem::operator==( const SfxPoolItem& rAttr ) const
{
    DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
    const SwPtrItem& rItem = (SwPtrItem&)rAttr;
    return ( pMisc == rItem.pMisc );
}

/*-----------------12.11.97 12:55-------------------------------
 SwUINumRuleItem fuer die NumTabPages der FormatNumRule/Stylisten
---------------------------------------------------------------*/
SwUINumRuleItem::SwUINumRuleItem( const SwNumRule& rRul, const USHORT nId )
    : SfxPoolItem( nId ), pRule( new SwNumRule( rRul ) )
{
}

SwUINumRuleItem::SwUINumRuleItem( const SwUINumRuleItem& rItem )
    : SfxPoolItem( rItem ),
    pRule( new SwNumRule( *rItem.pRule ))
{
}

 SwUINumRuleItem::~SwUINumRuleItem()
{
    delete pRule;
}

SfxPoolItem*  SwUINumRuleItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SwUINumRuleItem( *this );
}

int  SwUINumRuleItem::operator==( const SfxPoolItem& rAttr ) const
{
    DBG_ASSERT( SfxPoolItem::operator==(rAttr), "unequal types" );
    return *pRule == *((SwUINumRuleItem&)rAttr).pRule;
}

BOOL SwUINumRuleItem::QueryValue( uno::Any& rVal, BYTE /*nMemberId*/ ) const
{
    uno::Reference< container::XIndexReplace >xRules = new SwXNumberingRules(*pRule);
    rVal.setValue(&xRules, ::getCppuType((uno::Reference< container::XIndexReplace>*)0));
    return TRUE;
}
BOOL SwUINumRuleItem::PutValue( const uno::Any& rVal, BYTE /*nMemberId*/ )
{
    uno::Reference< container::XIndexReplace> xRulesRef;
    if(rVal >>= xRulesRef)
    {
        uno::Reference< lang::XUnoTunnel > xTunnel(xRulesRef, uno::UNO_QUERY);
        SwXNumberingRules* pSwXRules = xTunnel.is() ? reinterpret_cast<SwXNumberingRules*>(
                    xTunnel->getSomething(SwXNumberingRules::getUnoTunnelId())) : 0;
        if(pSwXRules)
        {
            *pRule = *pSwXRules->GetNumRule();
        }
    }
    return TRUE;
}
/* -----------------17.06.98 17:43-------------------
 *
 * --------------------------------------------------*/
SwBackgroundDestinationItem::SwBackgroundDestinationItem(USHORT  _nWhich, USHORT nValue) :
    SfxUInt16Item(_nWhich, nValue)
{
}
/* -----------------17.06.98 17:44-------------------
 *
 * --------------------------------------------------*/
SfxPoolItem*     SwBackgroundDestinationItem::Clone( SfxItemPool * /*pPool*/ ) const
{
    return new SwBackgroundDestinationItem(Which(), GetValue());
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: wrtundo.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: jp $ $Date: 2001-09-11 14:57:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#define _SVSTDARR_STRINGSDTOR

#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>                   // fuer Undo-Ids
#endif
#ifndef _SWDTFLVR_HXX
#include <swdtflvr.hxx>
#endif

#ifndef _WRTSH_HRC
#include <wrtsh.hrc>
#endif
#include <sfx2/sfx.hrc>

// Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden
// ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.

void SwWrtShell::Do( DoType eDoType, USHORT nCnt )
{
    StartAllAction();
    switch( eDoType )
    {
        case UNDO:
            // Modi zuruecksetzen
            EnterStdMode();
            SwEditShell::Undo(0, nCnt );
            break;
        case REDO:
            // Modi zuruecksetzen
            EnterStdMode();
            SwEditShell::Redo( nCnt );
            break;
        case REPEAT:
            SwEditShell::Repeat( nCnt );
            break;
    }
    EndAllAction();

    BOOL bCreateXSelection = FALSE;
    const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();
    if ( IsSelection() )
    {
        if ( bFrmSelected )
            UnSelectFrm();

        // Funktionspointer fuer das Aufheben der Selektion setzen
        // bei Cursor setzen
        fnKillSel = &SwWrtShell::ResetSelect;
        fnSetCrsr = &SwWrtShell::SetCrsrKillSel;
        bCreateXSelection = TRUE;
    }
    else if ( bFrmSelected )
    {
        EnterSelFrmMode();
        bCreateXSelection = TRUE;
    }
    else if( (CNT_GRF | CNT_OLE ) & GetCntType() )
    {
        SelectObj( GetCharRect().Pos() );
        EnterSelFrmMode();
        bCreateXSelection = TRUE;
    }

    if( bCreateXSelection )
        SwTransferable::CreateSelection( *this );

    // Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen
    //          Warum wird hier nicht immer ein CallChgLink gerufen?
    CallChgLnk();
}

String SwWrtShell::GetDoString( DoType eDoType ) const
{
    String aStr;
    USHORT nId = 0, nResStr;
    switch( eDoType )
    {
    case UNDO:
        nResStr = STR_UNDO;
        nId = GetUndoIds( &aStr );
        break;
    case REDO:
        nResStr = STR_REDO;
        nId = GetRedoIds( &aStr );
        break;
    }

    if( UNDO_END < nId )
    {
        aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager() )), 0 );
        if( UNDO_DRAWUNDO != nId )
            aStr += SW_RESSTR( UNDO_BASE + nId );
    }
    return aStr;
}

USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const
{
    SwUndoIds aIds;
    switch( eDoType )
    {
    case UNDO:
        GetUndoIds( 0, &aIds );
        break;
    case REDO:
        GetRedoIds( 0, &aIds );
        break;
    }

    String sList;
    for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )
    {
        const SwUndoIdAndName& rIdNm = *aIds[ n ];
        if( UNDO_DRAWUNDO != rIdNm.GetUndoId() )
            sList += String( ResId( UNDO_BASE + rIdNm.GetUndoId(), pSwResMgr ));
        else if( rIdNm.GetUndoStr() )
            sList += *rIdNm.GetUndoStr();
        else
        {
            ASSERT( !this, "no Undo/Redo Test set" );
        }
        sList += '\n';
    }
    rStrs.SetString( sList );
    return aIds.Count();
}

String SwWrtShell::GetRepeatString() const
{
    String aStr;
    USHORT nId = GetRepeatIds( &aStr );
    if( UNDO_END < nId )
    {
        aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );
        if( UNDO_DRAWUNDO != nId )
            aStr += SW_RESSTR( UNDO_BASE + nId );
    }
    return aStr;
}

/*************************************************************************

      $Log: not supported by cvs2svn $
      Revision 1.2  2001/04/09 07:28:55  tl
      Undo/Redo controller modifications

      Revision 1.1.1.1  2000/09/18 17:14:53  hr
      initial import

      Revision 1.53  2000/09/18 16:06:27  willem.vandorp
      OpenOffice header added.

      Revision 1.52  2000/07/27 21:01:41  jp
      Bug #76923#: Do - clamp the enterstdmode and Undo/Redo/Repeat call

      Revision 1.51  2000/03/03 15:17:06  os
      StarView remainders removed

      Revision 1.50  1998/04/15 14:35:34  OS
      STR_UNDO/REDO/REPEAT aus dem Sfx

      Rev 1.49   15 Apr 1998 16:35:34   OS
   STR_UNDO/REDO/REPEAT aus dem Sfx

      Rev 1.48   24 Nov 1997 14:35:02   MA
   includes

      Rev 1.47   03 Nov 1997 14:02:56   MA
   precomp entfernt

      Rev 1.46   22 Jan 1997 11:55:56   MA
   opt: bSelection entfernt

      Rev 1.45   11 Nov 1996 10:18:48   MA
   ResMgr

      Rev 1.44   31 Oct 1996 18:32:30   JP
   Bug #32918#: nach Undo der View sagen, das sich was getan hat

      Rev 1.43   29 Aug 1996 09:25:56   OS
   includes

      Rev 1.42   24 Nov 1995 16:59:06   OM
   PCH->PRECOMPILED

      Rev 1.41   19 Sep 1995 19:11:52   JP
   Bug 19431: Repeat funkt. wieder

      Rev 1.40   12 Sep 1995 17:59:32   JP
   Bug19137: vor Undo den Cursor in den StandardMode setzen

      Rev 1.39   28 Aug 1995 15:59:40   MA
   Renovierung: IDL, Shells, Textshell-Doktrin aufgegeben

      Rev 1.38   22 Aug 1995 17:30:04   JP
   GetUndo-/-Redo-/-RepeatIds: optional mit String-Ptr - DrawUndo-Objecte erzeuge die Strings selbst

      Rev 1.37   15 Aug 1995 19:52:20   JP
   Nach Undo/Redo kann der Cursor in OLE oder GRF stehen, selektieren dann den Frame

      Rev 1.36   27 Apr 1995 13:14:16   AMA
   Fix (JP): ResId-Ueberpruef. bei Undo

      Rev 1.35   23 Feb 1995 17:51:58   MA
   Rudimentaer Undo/Redo fuer Zeichenobjekte.

      Rev 1.34   08 Feb 1995 23:36:12   ER
   undo.hxx -> swundo.hxx wegen solar undo.hxx

      Rev 1.33   08 Feb 1995 19:01:30   JP
   UI-UndoIds ins undo.hxx verschoben

*************************************************************************/

<commit_msg>#105332# SwWrtShell::Do: Unable undo while doing Undo/Redo/Repeat<commit_after>/*************************************************************************
 *
 *  $RCSfile: wrtundo.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hbrinkm $ $Date: 2002-11-22 15:00:50 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#define _SVSTDARR_STRINGSDTOR

#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _SFXAPP_HXX //autogen
#include <sfx2/app.hxx>
#endif
#ifndef _SFXSLSTITM_HXX
#include <svtools/slstitm.hxx>
#endif

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>                   // fuer Undo-Ids
#endif
#ifndef _SWDTFLVR_HXX
#include <swdtflvr.hxx>
#endif

#ifndef _WRTSH_HRC
#include <wrtsh.hrc>
#endif
#include <sfx2/sfx.hrc>

// Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden
// ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.

void SwWrtShell::Do( DoType eDoType, USHORT nCnt )
{
    // #105332# save current state of DoesUndo() and disable undo.
    sal_Bool bSaveDoesUndo = DoesUndo();

    DoUndo(sal_False);
    StartAllAction();
    switch( eDoType )
    {
        case UNDO:
            // Modi zuruecksetzen
            EnterStdMode();
            SwEditShell::Undo(0, nCnt );
            break;
        case REDO:
            // Modi zuruecksetzen
            EnterStdMode();
            SwEditShell::Redo( nCnt );
            break;
        case REPEAT:
            SwEditShell::Repeat( nCnt );
            break;
    }
    EndAllAction();
    // #105332# restore undo state
    DoUndo(bSaveDoesUndo);

    BOOL bCreateXSelection = FALSE;
    const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();
    if ( IsSelection() )
    {
        if ( bFrmSelected )
            UnSelectFrm();

        // Funktionspointer fuer das Aufheben der Selektion setzen
        // bei Cursor setzen
        fnKillSel = &SwWrtShell::ResetSelect;
        fnSetCrsr = &SwWrtShell::SetCrsrKillSel;
        bCreateXSelection = TRUE;
    }
    else if ( bFrmSelected )
    {
        EnterSelFrmMode();
        bCreateXSelection = TRUE;
    }
    else if( (CNT_GRF | CNT_OLE ) & GetCntType() )
    {
        SelectObj( GetCharRect().Pos() );
        EnterSelFrmMode();
        bCreateXSelection = TRUE;
    }

    if( bCreateXSelection )
        SwTransferable::CreateSelection( *this );

    // Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen
    //          Warum wird hier nicht immer ein CallChgLink gerufen?
    CallChgLnk();
}

String SwWrtShell::GetDoString( DoType eDoType ) const
{
    String aStr;
    USHORT nId = 0, nResStr;
    switch( eDoType )
    {
    case UNDO:
        nResStr = STR_UNDO;
        nId = GetUndoIds( &aStr );
        break;
    case REDO:
        nResStr = STR_REDO;
        nId = GetRedoIds( &aStr );
        break;
    }

    if( UNDO_END < nId )
    {
        aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager() )), 0 );
        if( UNDO_DRAWUNDO != nId )
            aStr += SW_RESSTR( UNDO_BASE + nId );
    }
    return aStr;
}

USHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const
{
    SwUndoIds aIds;
    switch( eDoType )
    {
    case UNDO:
        GetUndoIds( 0, &aIds );
        break;
    case REDO:
        GetRedoIds( 0, &aIds );
        break;
    }

    String sList;
    for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )
    {
        const SwUndoIdAndName& rIdNm = *aIds[ n ];
        if( UNDO_DRAWUNDO != rIdNm.GetUndoId() )
            sList += String( ResId( UNDO_BASE + rIdNm.GetUndoId(), pSwResMgr ));
        else if( rIdNm.GetUndoStr() )
            sList += *rIdNm.GetUndoStr();
        else
        {
            ASSERT( !this, "no Undo/Redo Test set" );
        }
        sList += '\n';
    }
    rStrs.SetString( sList );
    return aIds.Count();
}

String SwWrtShell::GetRepeatString() const
{
    String aStr;
    USHORT nId = GetRepeatIds( &aStr );
    if( UNDO_END < nId )
    {
        aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );
        if( UNDO_DRAWUNDO != nId )
            aStr += SW_RESSTR( UNDO_BASE + nId );
    }
    return aStr;
}

/*************************************************************************

      $Log: not supported by cvs2svn $
      Revision 1.3  2001/09/11 14:57:42  jp
      Task #91678#: 'selection clipbord' implemented

      Revision 1.2  2001/04/09 07:28:55  tl
      Undo/Redo controller modifications

      Revision 1.1.1.1  2000/09/18 17:14:53  hr
      initial import

      Revision 1.53  2000/09/18 16:06:27  willem.vandorp
      OpenOffice header added.

      Revision 1.52  2000/07/27 21:01:41  jp
      Bug #76923#: Do - clamp the enterstdmode and Undo/Redo/Repeat call

      Revision 1.51  2000/03/03 15:17:06  os
      StarView remainders removed

      Revision 1.50  1998/04/15 14:35:34  OS
      STR_UNDO/REDO/REPEAT aus dem Sfx

      Rev 1.49   15 Apr 1998 16:35:34   OS
   STR_UNDO/REDO/REPEAT aus dem Sfx

      Rev 1.48   24 Nov 1997 14:35:02   MA
   includes

      Rev 1.47   03 Nov 1997 14:02:56   MA
   precomp entfernt

      Rev 1.46   22 Jan 1997 11:55:56   MA
   opt: bSelection entfernt

      Rev 1.45   11 Nov 1996 10:18:48   MA
   ResMgr

      Rev 1.44   31 Oct 1996 18:32:30   JP
   Bug #32918#: nach Undo der View sagen, das sich was getan hat

      Rev 1.43   29 Aug 1996 09:25:56   OS
   includes

      Rev 1.42   24 Nov 1995 16:59:06   OM
   PCH->PRECOMPILED

      Rev 1.41   19 Sep 1995 19:11:52   JP
   Bug 19431: Repeat funkt. wieder

      Rev 1.40   12 Sep 1995 17:59:32   JP
   Bug19137: vor Undo den Cursor in den StandardMode setzen

      Rev 1.39   28 Aug 1995 15:59:40   MA
   Renovierung: IDL, Shells, Textshell-Doktrin aufgegeben

      Rev 1.38   22 Aug 1995 17:30:04   JP
   GetUndo-/-Redo-/-RepeatIds: optional mit String-Ptr - DrawUndo-Objecte erzeuge die Strings selbst

      Rev 1.37   15 Aug 1995 19:52:20   JP
   Nach Undo/Redo kann der Cursor in OLE oder GRF stehen, selektieren dann den Frame

      Rev 1.36   27 Apr 1995 13:14:16   AMA
   Fix (JP): ResId-Ueberpruef. bei Undo

      Rev 1.35   23 Feb 1995 17:51:58   MA
   Rudimentaer Undo/Redo fuer Zeichenobjekte.

      Rev 1.34   08 Feb 1995 23:36:12   ER
   undo.hxx -> swundo.hxx wegen solar undo.hxx

      Rev 1.33   08 Feb 1995 19:01:30   JP
   UI-UndoIds ins undo.hxx verschoben

*************************************************************************/

<|endoftext|>


<commit_before><commit_msg>add a TODO to exchange<commit_after><|endoftext|>


<commit_before>#ifndef SDR_H_
#define SDR_H_

#include <vector>
#include <array>
#include <bitset>
#include <iostream>
#include <utility>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <unordered_set>

namespace sdr
{

typedef std::size_t position_t;
typedef std::size_t width_t;

// this holds all of the traits for a single concept
// ie - if width is 1024, this could hold up to 1024 values between 0 and 1024
struct concept
{
    std::vector<position_t> data;

    // for vector of positions we assume the data has already been dealt with
    concept(const std::vector<position_t> & input) : data(input)
    {}

    // otherwise we assume that is hasn't, thus we only add non zero fields
    template <typename T>
    concept(const T & input) : data()
    {
        for(std::size_t i=0; i < input.size(); ++i) {
            if(input[i]) {
                data.push_back(i);
            }
        }
    }
};

template <width_t Width>
struct node
{
    // store the positions of all set bits from 0 -> width
    std::unordered_set<position_t> positions;

    node(const concept & concept) : positions(concept.data.begin(), concept.data.end())
    {}

    void fill(const concept & concept)
    {
        std::copy(concept.data.begin(), concept.data.end(), std::inserter(positions, positions.begin()));
    }

    void clear()
    {
        positions.clear();
    }

    void print() const
    {
        const std::size_t sroot = std::sqrt(Width);

        for(std::size_t y=0; y < sroot; ++y) {
            for(std::size_t x=0; x < sroot; ++x) {
                std::cout << (positions.count((y * sroot) + x) ? '1' : '0');
            }

            std::cout << std::endl;
        }
    }
};

template <width_t Width>
struct bank
{
    // all inputs we have ever received, we store here compressed into storage
    std::vector<node<Width>> storage;

    // this holds our sets of vectors for easy comparison of different objects in storage
    std::array<std::unordered_set<position_t>, Width> bitmap;

    bank() : storage(), bitmap()
    {}

    void print(const position_t pos) const
    {
        storage[pos].print();
    }

    position_t insert(const concept & concept)
    {
        storage.push_back(node<Width>(concept));

        const position_t last_pos = storage.size() - 1;

        for(position_t pos : concept.data) {
            bitmap[pos].insert(last_pos);
        }

        return last_pos;
    }

    void update(const position_t pos, const concept & concept)
    {
        node<Width> & node = storage[pos];

        for(position_t i : node.positions) {
            bitmap[i].erase(pos);
        }

        node.clear();

        node.fill(concept);

        for(position_t p : node.positions) {
            bitmap[p].insert(pos);
        }
    }

    // find amount of matching bits between two vectors
    std::size_t similarity(const position_t a, const position_t b) const
    {
        std::size_t result = 0;

        for(position_t pos : storage[a].positions) {
            result += bitmap[pos].count(b);
        }

        return result;
    }

    // find amount of matching bits between two vectors
    double weighted_similarity(const position_t a, const position_t b, const std::array<double, Width> & weights) const
    {
        double result = 0;

        for(position_t pos : storage[a].positions) {
            result += bitmap[pos].count(b) * weights[pos];
        }

        return result;
    }

    // find similarity of one object compared to the OR'd result of a list of objects
    std::size_t union_similarity(const position_t pos, const std::vector<position_t> & positions) const
    {
        std::bitset<Width> punions;

        for(const position_t ppos : positions) {
            for(const position_t spos : storage[ppos].positions) {
                punions.set(spos);
            }
        }

        std::size_t result = 0;

        for(const position_t cmp : storage[pos].positions) {
            result += punions[cmp];
        }

        return result;
    }

    // find similarity of one object compared to the OR'd result of a list of objects
    double weighted_union_similarity(const position_t pos, const std::vector<position_t> & positions, const std::array<double, Width> & weights) const
    {
        std::bitset<Width> punions;

        for(const position_t ppos : positions) {
            for(const position_t spos : storage[ppos].positions) {
                punions.set(spos);
            }
        }

        double result = 0;

        for(const position_t cmp : storage[pos].positions) {
            result += punions[cmp] * weights[cmp];
        }

        return result;
    }

    // find most similar to object at pos
    // first refers to position
    // second refers to matching number of bits
    std::vector<std::pair<position_t, std::size_t>> closest(const position_t pos, const std::size_t amount) const
    {
        std::vector<position_t> idx(storage.size());
        std::vector<unsigned>     v(storage.size());

        std::iota(idx.begin(), idx.end(), 0);

        // count matching bits for each
        for(const position_t spos : storage[pos].positions) {
            for(const position_t bpos : bitmap[spos]) {
                ++v[bpos];
            }
        }

        // we dont care about our self similarity
        v[pos] = 0;

        // if there are less than amount in storage, just return amount that exist
        const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);

        std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](
            const position_t a,
            const position_t b
        ) {
            return v[a] > v[b];
        });

        // create std::pair for result
        std::vector<std::pair<position_t, std::size_t>> ret;
        ret.reserve(partial_amount);

        for(std::size_t i=0; i<partial_amount; ++i) {
            const auto m = idx[i];
            ret.push_back(std::make_pair(m, static_cast<std::size_t>(v[m])));
        }

        return ret;
    }

    // find most similar to object at pos
    // first refers to position
    // second refers to matching number of bits
    std::vector<std::pair<position_t, double>> weighted_closest(const position_t pos, const std::size_t amount, const std::array<double, Width> & weights) const
    {
        std::vector<position_t> idx(storage.size());
        std::vector<double>       v(storage.size());

        std::iota(idx.begin(), idx.end(), 0);

        // count matching bits for each
        for(const position_t spos : storage[pos].positions) {
            for(const position_t bpos : bitmap[spos]) {
                v[bpos] += weights[spos];
            }
        }

        // we dont care about our self similarity
        v[pos] = 0.0;

        // if there are less than amount in storage, just return amount that exist
        const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);

        std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](
            const position_t a,
            const position_t b
        ) {
            return v[a] > v[b];
        });

        // create std::pair for result
        std::vector<std::pair<position_t, double>> ret;
        ret.reserve(partial_amount);

        for(std::size_t i=0; i<partial_amount; ++i) {
            const auto m = idx[i];
            ret.push_back(std::make_pair(m, v[m]));
        }

        return ret;
    }

    // return all items matching all in data
    std::vector<position_t> matching(const concept & concept) const
    {
        std::unordered_set<position_t> matching;

        for(const std::size_t item : concept.data) {
            for(const std::size_t pos : bitmap[item]) {
                for(const std::size_t m : concept.data) {
                    if(bitmap[m].count(pos) == 0) {
                        goto skip;
                    }
                }

                matching.insert(pos);
                skip:;
            }
        }

        return std::vector<position_t>(matching.begin(), matching.end());
    }

    // has to match amount in data
    std::vector<position_t> matching(const concept & concept, const std::size_t amount) const
    {
        std::unordered_set<position_t> matching;

        for(const std::size_t item : concept.data) {
            for(const std::size_t pos : bitmap[item]) {
                std::size_t amount_matching = 0;

                for(const std::size_t m : concept.data) {
                    amount_matching += bitmap[m].count(pos);
                }

                if(amount_matching >= amount) {
                    matching.insert(pos);
                }
            }
        }

        return std::vector<position_t>(matching.begin(), matching.end());
    }

    // has to match amount in data
    std::vector<position_t> weighted_matching(const std::vector<position_t> & data, const double amount, const std::array<double, Width> & weights) const
    {
        std::unordered_set<position_t> matching;

        for(const std::size_t item : data) {
            for(const std::size_t pos : bitmap[item]) {
                double amount_matching = 0;

                for(const std::size_t m : data) {
                    amount_matching += bitmap[m].count(pos) * weights[m];
                }

                if(amount_matching >= amount) {
                    matching.insert(pos);
                }
            }
        }

        return std::vector<position_t>(matching.begin(), matching.end());
    }
};

} //namespace sdr

#endif
<commit_msg>more docs<commit_after>#ifndef SDR_H_
#define SDR_H_

#include <vector>
#include <array>
#include <bitset>
#include <iostream>
#include <utility>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <unordered_set>

namespace sdr
{

typedef std::size_t position_t;
typedef std::size_t width_t;

// this holds all of the traits for a single concept
// ie - if width is 1024, this could hold up to 1024 values between 0 and 1024
struct concept
{
    std::vector<position_t> data;

    // for vector of positions we assume the data has already been dealt with
    concept(const std::vector<position_t> & input) : data(input)
    {}

    // otherwise we assume that is hasn't, thus we only add non zero fields
    template <typename T> concept(const T & input) : data()
    {
        for(std::size_t i=0; i < input.size(); ++i) {
            if(input[i]) {
                data.push_back(i);
            }
        }
    }
};

// represents a concept in storage
// designed to be able to be quickly queried and modified
template <width_t Width> struct node
{
    // store the positions of all set bits from 0 -> width
    std::unordered_set<position_t> positions;

    node(const concept & concept) : positions(concept.data.begin(), concept.data.end())
    {}

    void fill(const concept & concept)
    {
        std::copy(concept.data.begin(), concept.data.end(), std::inserter(positions, positions.begin()));
    }

    void clear()
    {
        positions.clear();
    }

    void print() const
    {
        const std::size_t sroot = std::sqrt(Width);

        for(std::size_t y=0; y < sroot; ++y) {
            for(std::size_t x=0; x < sroot; ++x) {
                std::cout << (positions.count((y * sroot) + x) ? '1' : '0');
            }

            std::cout << std::endl;
        }
    }
};

// this is the memory bank for the sdr memory unit
template <width_t Width> struct bank
{
    // all inputs we have ever received, we store here compressed into storage
    std::vector<node<Width>> storage;

    // this holds our sets of vectors for easy comparison of different objects in storage
    std::array<std::unordered_set<position_t>, Width> bitmap;

    bank() : storage(), bitmap()
    {}

    void print(const position_t pos) const
    {
        storage[pos].print();
    }

    position_t insert(const concept & concept)
    {
        storage.push_back(node<Width>(concept));

        const position_t last_pos = storage.size() - 1;

        for(position_t pos : concept.data) {
            bitmap[pos].insert(last_pos);
        }

        return last_pos;
    }

    void update(const position_t pos, const concept & concept)
    {
        node<Width> & node = storage[pos];

        for(position_t i : node.positions) {
            bitmap[i].erase(pos);
        }

        node.clear();

        node.fill(concept);

        for(position_t p : node.positions) {
            bitmap[p].insert(pos);
        }
    }

    // find amount of matching bits between two vectors
    std::size_t similarity(const position_t a, const position_t b) const
    {
        std::size_t result = 0;

        for(position_t pos : storage[a].positions) {
            result += bitmap[pos].count(b);
        }

        return result;
    }

    // find amount of matching bits between two vectors
    double weighted_similarity(const position_t a, const position_t b, const std::array<double, Width> & weights) const
    {
        double result = 0;

        for(position_t pos : storage[a].positions) {
            result += bitmap[pos].count(b) * weights[pos];
        }

        return result;
    }

    // find similarity of one object compared to the OR'd result of a list of objects
    std::size_t union_similarity(const position_t pos, const std::vector<position_t> & positions) const
    {
        std::bitset<Width> punions;

        for(const position_t ppos : positions) {
            for(const position_t spos : storage[ppos].positions) {
                punions.set(spos);
            }
        }

        std::size_t result = 0;

        for(const position_t cmp : storage[pos].positions) {
            result += punions[cmp];
        }

        return result;
    }

    // find similarity of one object compared to the OR'd result of a list of objects
    double weighted_union_similarity(const position_t pos, const std::vector<position_t> & positions, const std::array<double, Width> & weights) const
    {
        std::bitset<Width> punions;

        for(const position_t ppos : positions) {
            for(const position_t spos : storage[ppos].positions) {
                punions.set(spos);
            }
        }

        double result = 0;

        for(const position_t cmp : storage[pos].positions) {
            result += punions[cmp] * weights[cmp];
        }

        return result;
    }

    // find most similar to object at pos
    // first refers to position
    // second refers to matching number of bits
    std::vector<std::pair<position_t, std::size_t>> closest(const position_t pos, const std::size_t amount) const
    {
        std::vector<position_t> idx(storage.size());
        std::vector<unsigned>     v(storage.size());

        std::iota(idx.begin(), idx.end(), 0);

        // count matching bits for each
        for(const position_t spos : storage[pos].positions) {
            for(const position_t bpos : bitmap[spos]) {
                ++v[bpos];
            }
        }

        // we dont care about our self similarity
        v[pos] = 0;

        // if there are less than amount in storage, just return amount that exist
        const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);

        std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](
            const position_t a,
            const position_t b
        ) {
            return v[a] > v[b];
        });

        // create std::pair for result
        std::vector<std::pair<position_t, std::size_t>> ret;
        ret.reserve(partial_amount);

        for(std::size_t i=0; i<partial_amount; ++i) {
            const auto m = idx[i];
            ret.push_back(std::make_pair(m, static_cast<std::size_t>(v[m])));
        }

        return ret;
    }

    // find most similar to object at pos
    // first refers to position
    // second refers to matching number of bits
    std::vector<std::pair<position_t, double>> weighted_closest(const position_t pos, const std::size_t amount, const std::array<double, Width> & weights) const
    {
        std::vector<position_t> idx(storage.size());
        std::vector<double>       v(storage.size());

        std::iota(idx.begin(), idx.end(), 0);

        // count matching bits for each
        for(const position_t spos : storage[pos].positions) {
            for(const position_t bpos : bitmap[spos]) {
                v[bpos] += weights[spos];
            }
        }

        // we dont care about our self similarity
        v[pos] = 0.0;

        // if there are less than amount in storage, just return amount that exist
        const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);

        std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](
            const position_t a,
            const position_t b
        ) {
            return v[a] > v[b];
        });

        // create std::pair for result
        std::vector<std::pair<position_t, double>> ret;
        ret.reserve(partial_amount);

        for(std::size_t i=0; i<partial_amount; ++i) {
            const auto m = idx[i];
            ret.push_back(std::make_pair(m, v[m]));
        }

        return ret;
    }

    // return all items matching all in data
    std::vector<position_t> matching(const concept & concept) const
    {
        std::unordered_set<position_t> matching;

        for(const std::size_t item : concept.data) {
            for(const std::size_t pos : bitmap[item]) {
                for(const std::size_t m : concept.data) {
                    if(bitmap[m].count(pos) == 0) {
                        goto skip;
                    }
                }

                matching.insert(pos);
                skip:;
            }
        }

        return std::vector<position_t>(matching.begin(), matching.end());
    }

    // has to match amount in data
    std::vector<position_t> matching(const concept & concept, const std::size_t amount) const
    {
        std::unordered_set<position_t> matching;

        for(const std::size_t item : concept.data) {
            for(const std::size_t pos : bitmap[item]) {
                std::size_t amount_matching = 0;

                for(const std::size_t m : concept.data) {
                    amount_matching += bitmap[m].count(pos);
                }

                if(amount_matching >= amount) {
                    matching.insert(pos);
                }
            }
        }

        return std::vector<position_t>(matching.begin(), matching.end());
    }

    // has to match amount in data
    std::vector<position_t> weighted_matching(const std::vector<position_t> & data, const double amount, const std::array<double, Width> & weights) const
    {
        std::unordered_set<position_t> matching;

        for(const std::size_t item : data) {
            for(const std::size_t pos : bitmap[item]) {
                double amount_matching = 0;

                for(const std::size_t m : data) {
                    amount_matching += bitmap[m].count(pos) * weights[m];
                }

                if(amount_matching >= amount) {
                    matching.insert(pos);
                }
            }
        }

        return std::vector<position_t>(matching.begin(), matching.end());
    }
};

} //namespace sdr

#endif
<|endoftext|>


<commit_before>/*
 * =====================================================================================
 *
 *       Filename:  mpu9150_node.cpp
 *
 *    Description: ROS package that launches a node and publishes
 *	  the Invensense MPU-9150 in the format Imu.msgs and MagneticField.msgs to the topics
 *    /imu/data_raw and /imu/mag
 *
 *        Version:  1.1
 *        Created:  27/07/13 15:06:50
 *       Revision:  Morgan Dykshorn <mdd27@vt.edu> 2015
 *
 *         Author:  Víctor Mayoral Vilches <v.mayoralv@gmail.com>
 *
 * =====================================================================================
 */
#include "ros/ros.h"
#include "std_msgs/String.h"
//include IMU message, geometry message quaternion, geometry message vector3, and magnetic field
#include "sensor_msgs/Imu.h"
#include "geometry_msgs/Quaternion.h"
#include "geometry_msgs/Vector3.h"
#include "sensor_msgs/MagneticField.h"
#include <sstream>

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>
#include <errno.h>

// Needed when mixing C and C++ code/libraries
#ifdef __cplusplus
    extern "C" {
#endif
        #include "mpu9150.h"
        #include "linux_glue.h"
        #include "local_defaults.h"

#ifdef __cplusplus
    }
#endif

//calibration function
int set_cal(int mag, char *cal_file);
//
void register_sig_handler();
void sigint_handler(int sig);

int done;

int main(int argc, char **argv)
{
  ros::init(argc, argv, "mpu9150_node");
  ros::NodeHandle n;
  //creates publisher of IMU message
  ros::Publisher pub = n.advertise<sensor_msgs::Imu>("imu/data_raw", 1000);
  //creates publisher of Magnetic FIeld message
  ros::Publisher pubM = n.advertise<sensor_msgs::MagneticField>("imu/mag", 1000);
  ros::Rate loop_rate(10);

  /* Init the sensor the values are hardcoded at the local_defaults.h file */
    int opt, len;
	int i2c_bus = DEFAULT_I2C_BUS;
	int sample_rate = DEFAULT_SAMPLE_RATE_HZ;
	int yaw_mix_factor = DEFAULT_YAW_MIX_FACTOR;
	int verbose = 0;
	char *mag_cal_file = NULL;
	char *accel_cal_file = NULL;
	//creates object of mpudata_t
	mpudata_t mpu;

    // Initialize the MPU-9150
	register_sig_handler();
	mpu9150_set_debug(verbose);
	if (mpu9150_init(i2c_bus, sample_rate, yaw_mix_factor))
		exit(1);
	set_cal(0, accel_cal_file);
	set_cal(1, mag_cal_file);
	if (accel_cal_file)
		free(accel_cal_file);
	if (mag_cal_file)
		free(mag_cal_file);

	if (sample_rate == 0)
		return -1;

  /**
   * A count of how many messages we have sent. This is used to create
   * a unique string for each message.
   */
  int count = 0;
  while (ros::ok())
  {
  	//creates objects of each message type
  	//IMU Message
    sensor_msgs::Imu msgIMU;
    std_msgs::String header;
    geometry_msgs::Quaternion orientation;
    geometry_msgs::Vector3 angular_velocity;
    geometry_msgs::Vector3 linear_acceleration;
    //magnetometer message
    sensor_msgs::MagneticField msgMAG;
    geometry_msgs::Vector3 magnetic_field;

//modified to output in the format of IMU message
	if (mpu9150_read(&mpu) == 0) {
		//IMU Message
		//sets up header for IMU message
		msgIMU.header.seq = count;
		msgIMU.header.stamp.sec = ros::Time::now().toSec();
		msgIMU.header.frame_id = "/base_link";
		//adds data to the sensor message
		//orientation
		msgIMU.orientation.x = mpu.fusedQuat[QUAT_X];
		msgIMU.orientation.y = mpu.fusedQuat[QUAT_Y];
		msgIMU.orientation.z = mpu.fusedQuat[QUAT_Z];
		msgIMU.orientation.w = mpu.fusedQuat[QUAT_W];
		//msgIMU.orientation_covariance[0] =
		//angular velocity
		msgIMU.angular_velocity.x = mpu.fusedEuler[VEC3_X] * RAD_TO_DEGREE;
		msgIMU.angular_velocity.y = mpu.fusedEuler[VEC3_Y] * RAD_TO_DEGREE;
		msgIMU.angular_velocity.z = mpu.fusedEuler[VEC3_Z] * RAD_TO_DEGREE;
		//msgIMU.angular_velocity_covariance[] =
		//linear acceleration
		msgIMU.linear_acceleration.x = mpu.calibratedAccel[VEC3_X];
		msgIMU.linear_acceleration.y = mpu.calibratedAccel[VEC3_Y];
		msgIMU.linear_acceleration.z = mpu.calibratedAccel[VEC3_Z];
		//msgIMU.linear_acceleration_covariance[] =

		//Magnetometer Message
		//sets up header
		msgMAG.header.seq = count;
		msgMAG.header.stamp.sec = ros::Time::now().toSec();
		msgMAG.header.frame_id = "/base_link";
		//adds data to magnetic field message
		msgMAG.magnetic_field.x = mpu.calibratedMag[VEC3_X];
		msgMAG.magnetic_field.y = mpu.calibratedMag[VEC3_Y];
		msgMAG.magnetic_field.z = mpu.calibratedMag[VEC3_Z];
		//fills the list with zeros as per message spec when no covariance is known
		//msgMAG.magnetic_field_covariance[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
	}

	//publish both messages
    pub.publish(msgIMU);
    pubM.publish(msgMAG);
    ros::spinOnce();
    loop_rate.sleep();
    ++count;
  }
  mpu9150_exit();
  return 0;
}

int set_cal(int mag, char *cal_file)
{
	int i;
	FILE *f;
	char buff[32];
	long val[6];
	caldata_t cal;

	if (cal_file) {
		f = fopen(cal_file, "r");

		if (!f) {
			perror("open(<cal-file>)");
			return -1;
		}
	}
	else {
		if (mag) {
			f = fopen("./magcal.txt", "r");

			if (!f) {
				printf("Default magcal.txt not found\n");
				return 0;
			}
		}
		else {
			f = fopen("./accelcal.txt", "r");

			if (!f) {
				printf("Default accelcal.txt not found\n");
				return 0;
			}
		}
	}

	memset(buff, 0, sizeof(buff));

	for (i = 0; i < 6; i++) {
		if (!fgets(buff, 20, f)) {
			printf("Not enough lines in calibration file\n");
			break;
		}

		val[i] = atoi(buff);

		if (val[i] == 0) {
			printf("Invalid cal value: %s\n", buff);
			break;
		}
	}

	fclose(f);

	if (i != 6)
		return -1;

	cal.offset[0] = (short)((val[0] + val[1]) / 2);
	cal.offset[1] = (short)((val[2] + val[3]) / 2);
	cal.offset[2] = (short)((val[4] + val[5]) / 2);

	cal.range[0] = (short)(val[1] - cal.offset[0]);
	cal.range[1] = (short)(val[3] - cal.offset[1]);
	cal.range[2] = (short)(val[5] - cal.offset[2]);

	if (mag)
		mpu9150_set_mag_cal(&cal);
	else
		mpu9150_set_accel_cal(&cal);

	return 0;
}

void register_sig_handler()
{
	struct sigaction sia;

	bzero(&sia, sizeof sia);
	sia.sa_handler = sigint_handler;

	if (sigaction(SIGINT, &sia, NULL) < 0) {
		perror("sigaction(SIGINT)");
		exit(1);
	}
}

void sigint_handler(int sig)
{
	done = 1;
}<commit_msg>added loop control<commit_after>/*
 * =====================================================================================
 *
 *       Filename:  mpu9150_node.cpp
 *
 *    Description: ROS package that launches a node and publishes
 *	  the Invensense MPU-9150 in the format Imu.msgs and MagneticField.msgs to the topics
 *    /imu/data_raw and /imu/mag
 *
 *        Version:  1.1
 *        Created:  27/07/13 15:06:50
 *       Revision:  Morgan Dykshorn <mdd27@vt.edu> 2015
 *
 *         Author:  Víctor Mayoral Vilches <v.mayoralv@gmail.com>
 *
 * =====================================================================================
 */
#include "ros/ros.h"
#include "std_msgs/String.h"
//include IMU message, geometry message quaternion, geometry message vector3, and magnetic field
#include "sensor_msgs/Imu.h"
#include "geometry_msgs/Quaternion.h"
#include "geometry_msgs/Vector3.h"
#include "sensor_msgs/MagneticField.h"
#include <sstream>

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <getopt.h>
#include <errno.h>

// Needed when mixing C and C++ code/libraries
#ifdef __cplusplus
    extern "C" {
#endif
        #include "mpu9150.h"
        #include "linux_glue.h"
        #include "local_defaults.h"

#ifdef __cplusplus
    }
#endif

//calibration function
int set_cal(int mag, char *cal_file);
//
void register_sig_handler();
void sigint_handler(int sig);

int done;

int main(int argc, char **argv)
{
  ros::init(argc, argv, "mpu9150_node");
  ros::NodeHandle n;
  //creates publisher of IMU message
  ros::Publisher pub = n.advertise<sensor_msgs::Imu>("imu/data_raw", 1000);
  //creates publisher of Magnetic FIeld message
  ros::Publisher pubM = n.advertise<sensor_msgs::MagneticField>("imu/mag", 1000);
  ros::Rate loop_rate(10);

  /* Init the sensor the values are hardcoded at the local_defaults.h file */
    int opt, len;
	int i2c_bus = DEFAULT_I2C_BUS;
	int sample_rate = DEFAULT_SAMPLE_RATE_HZ;
	int yaw_mix_factor = DEFAULT_YAW_MIX_FACTOR;
	int verbose = 0;
	char *mag_cal_file = NULL;
	char *accel_cal_file = NULL;
	//creates object of mpudata_t
	mpudata_t mpu;

    // Initialize the MPU-9150
	register_sig_handler();
	mpu9150_set_debug(verbose);
	if (mpu9150_init(i2c_bus, sample_rate, yaw_mix_factor))
		exit(1);
	set_cal(0, accel_cal_file);
	set_cal(1, mag_cal_file);
	if (accel_cal_file)
		free(accel_cal_file);
	if (mag_cal_file)
		free(mag_cal_file);

	if (sample_rate == 0)
		return -1;

    // ROS loop config
	loop_delay = (1000 / sample_rate) - 2;
	printf("\nEntering MPU read loop (ctrl-c to exit)\n\n");
	linux_delay_ms(loop_delay);

  /**
   * A count of how many messages we have sent. This is used to create
   * a unique string for each message.
   */
  int count = 0;
  while (ros::ok())
  {
  	//creates objects of each message type
  	//IMU Message
    sensor_msgs::Imu msgIMU;
    std_msgs::String header;
    geometry_msgs::Quaternion orientation;
    geometry_msgs::Vector3 angular_velocity;
    geometry_msgs::Vector3 linear_acceleration;
    //magnetometer message
    sensor_msgs::MagneticField msgMAG;
    geometry_msgs::Vector3 magnetic_field;

//modified to output in the format of IMU message
	if (mpu9150_read(&mpu) == 0) {
		//IMU Message
		//sets up header for IMU message
		msgIMU.header.seq = count;
		msgIMU.header.stamp.sec = ros::Time::now().toSec();
		msgIMU.header.frame_id = "/base_link";
		//adds data to the sensor message
		//orientation
		msgIMU.orientation.x = mpu.fusedQuat[QUAT_X];
		msgIMU.orientation.y = mpu.fusedQuat[QUAT_Y];
		msgIMU.orientation.z = mpu.fusedQuat[QUAT_Z];
		msgIMU.orientation.w = mpu.fusedQuat[QUAT_W];
		//msgIMU.orientation_covariance[0] =
		//angular velocity
		msgIMU.angular_velocity.x = mpu.fusedEuler[VEC3_X] * RAD_TO_DEGREE;
		msgIMU.angular_velocity.y = mpu.fusedEuler[VEC3_Y] * RAD_TO_DEGREE;
		msgIMU.angular_velocity.z = mpu.fusedEuler[VEC3_Z] * RAD_TO_DEGREE;
		//msgIMU.angular_velocity_covariance[] =
		//linear acceleration
		msgIMU.linear_acceleration.x = mpu.calibratedAccel[VEC3_X];
		msgIMU.linear_acceleration.y = mpu.calibratedAccel[VEC3_Y];
		msgIMU.linear_acceleration.z = mpu.calibratedAccel[VEC3_Z];
		//msgIMU.linear_acceleration_covariance[] =

		//Magnetometer Message
		//sets up header
		msgMAG.header.seq = count;
		msgMAG.header.stamp.sec = ros::Time::now().toSec();
		msgMAG.header.frame_id = "/base_link";
		//adds data to magnetic field message
		msgMAG.magnetic_field.x = mpu.calibratedMag[VEC3_X];
		msgMAG.magnetic_field.y = mpu.calibratedMag[VEC3_Y];
		msgMAG.magnetic_field.z = mpu.calibratedMag[VEC3_Z];
		//fills the list with zeros as per message spec when no covariance is known
		//msgMAG.magnetic_field_covariance[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
	}

	//publish both messages
    pub.publish(msgIMU);
    pubM.publish(msgMAG);
    ros::spinOnce();
    loop_rate.sleep();
    ++count;
  }
  mpu9150_exit();
  return 0;
}

int set_cal(int mag, char *cal_file)
{
	int i;
	FILE *f;
	char buff[32];
	long val[6];
	caldata_t cal;

	if (cal_file) {
		f = fopen(cal_file, "r");

		if (!f) {
			perror("open(<cal-file>)");
			return -1;
		}
	}
	else {
		if (mag) {
			f = fopen("./magcal.txt", "r");

			if (!f) {
				printf("Default magcal.txt not found\n");
				return 0;
			}
		}
		else {
			f = fopen("./accelcal.txt", "r");

			if (!f) {
				printf("Default accelcal.txt not found\n");
				return 0;
			}
		}
	}

	memset(buff, 0, sizeof(buff));

	for (i = 0; i < 6; i++) {
		if (!fgets(buff, 20, f)) {
			printf("Not enough lines in calibration file\n");
			break;
		}

		val[i] = atoi(buff);

		if (val[i] == 0) {
			printf("Invalid cal value: %s\n", buff);
			break;
		}
	}

	fclose(f);

	if (i != 6)
		return -1;

	cal.offset[0] = (short)((val[0] + val[1]) / 2);
	cal.offset[1] = (short)((val[2] + val[3]) / 2);
	cal.offset[2] = (short)((val[4] + val[5]) / 2);

	cal.range[0] = (short)(val[1] - cal.offset[0]);
	cal.range[1] = (short)(val[3] - cal.offset[1]);
	cal.range[2] = (short)(val[5] - cal.offset[2]);

	if (mag)
		mpu9150_set_mag_cal(&cal);
	else
		mpu9150_set_accel_cal(&cal);

	return 0;
}

void register_sig_handler()
{
	struct sigaction sia;

	bzero(&sia, sizeof sia);
	sia.sa_handler = sigint_handler;

	if (sigaction(SIGINT, &sia, NULL) < 0) {
		perror("sigaction(SIGINT)");
		exit(1);
	}
}

void sigint_handler(int sig)
{
	done = 1;
}<|endoftext|>


<commit_before>/*
    Persons Model Contact Item
    Represents person's contact item in the model
    Copyright (C) 2012  Martin Klapetek <martin.klapetek@gmail.com>
    Copyright (C) 2012  Aleix Pol Gonzalez <aleixpol@blue-systems.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "persons-model-contact-item.h"
#include <KIcon>
#include <KDebug>
#include <Nepomuk/Vocabulary/NCO>
#include <Soprano/Vocabulary/NAO>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <Nepomuk/Resource>
#include <Nepomuk/Variant>
#include <Nepomuk/ResourceManager>

class PersonsModelContactItemPrivate {
public:
    QHash<QUrl, QVariant> data;
};

PersonsModelContactItem::PersonsModelContactItem(const QUrl& uri, const QString& displayName)
    : d_ptr(new PersonsModelContactItemPrivate)
{
    setData(uri, PersonsModel::UriRole);
    setText(displayName);

    refreshIcon();
}

PersonsModelContactItem::~PersonsModelContactItem()
{
    delete d_ptr;
}

QMap<PersonsModel::ContactType, QIcon> initializeTypeIcons()
{
    QMap<PersonsModel::ContactType, QIcon> ret;
    ret.insert(PersonsModel::Email, QIcon::fromTheme(QLatin1String("mail-mark-unread")));
    ret.insert(PersonsModel::IM, QIcon::fromTheme(QLatin1String("im-user")));
    ret.insert(PersonsModel::Phone, QIcon::fromTheme(QLatin1String("phone")));
    ret.insert(PersonsModel::MobilePhone, QIcon::fromTheme(QLatin1String("phone")));
    ret.insert(PersonsModel::Postal, QIcon::fromTheme(QLatin1String("mail-message")));
    return ret;
}

static QMap<PersonsModel::ContactType, QIcon> s_contactTypeMap = initializeTypeIcons();

void PersonsModelContactItem::refreshIcon()
{
    PersonsModel::ContactType type = (PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt();
    setIcon(s_contactTypeMap[type]);
}

void PersonsModelContactItem::addData(const QUrl &key, const QVariant &value)
{
    if(value.isNull())
        return;

    if(Nepomuk::Vocabulary::NCO::imNickname() == key) {
        setText(value.toString());
    } else if (Nepomuk::Vocabulary::NCO::imID() == key) {
        setType(PersonsModel::IM);
    } else if (Nepomuk::Vocabulary::NCO::hasEmailAddress() == key) {
        setType(PersonsModel::Email);
    }else if (Nepomuk::Vocabulary::NCO::emailAddress() == key) {
        setText(value.toString());
    }

    Q_D(PersonsModelContactItem);
//     kDebug() << "Inserting" << value << "(" << key << ")";
    d->data.insert(key, value);
    emitDataChanged();
}

QVariant PersonsModelContactItem::dataValue(const QUrl &key)
{
    Q_D(PersonsModelContactItem);
    return d->data.value(key);
}

QUrl PersonsModelContactItem::uri() const
{
    return data(PersonsModel::UriRole).toUrl();
}

void PersonsModelContactItem::setType (PersonsModel::ContactType type)
{
    setData(type, PersonsModel::ContactTypeRole);
    refreshIcon();
}

QVariant PersonsModelContactItem::data(int role) const
{
    Q_D(const PersonsModelContactItem);
    switch(role) {
        case PersonsModel::NickRole: return d->data.value(Nepomuk::Vocabulary::NCO::imNickname());
        case PersonsModel::PhoneRole: return d->data.value(Nepomuk::Vocabulary::NCO::phoneNumber());
        case PersonsModel::EmailRole: return d->data.value(Nepomuk::Vocabulary::NCO::emailAddress());
        case PersonsModel::IMRole: return d->data.value(Nepomuk::Vocabulary::NCO::imID());
        case PersonsModel::PhotoRole: {
            QHash<QUrl, QVariant>::const_iterator it = d->data.constFind(Nepomuk::Vocabulary::NCO::photo());
            if(it==d->data.constEnd()) {
                const QString query = QString::fromLatin1("select ?url where { %1 nco:photo ?phRes. ?phRes nie:url ?url . }")
                                                          .arg( Soprano::Node::resourceToN3(uri()) );
                Soprano::Model* model = Nepomuk::ResourceManager::instance()->mainModel();
                Soprano::QueryResultIterator qit = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );

                QUrl url;
                if( qit.next() ) {
                    url = qit["url"].uri();
                }
                it = d_ptr->data.insert(Nepomuk::Vocabulary::NCO::photo(), url);
            }
            return it!=d->data.constEnd() ? it.value() : QVariant();
        }
    }
    return QStandardItem::data(role);
}
<commit_msg>Implement the ContactIdRole for contacts<commit_after>/*
    Persons Model Contact Item
    Represents person's contact item in the model
    Copyright (C) 2012  Martin Klapetek <martin.klapetek@gmail.com>
    Copyright (C) 2012  Aleix Pol Gonzalez <aleixpol@blue-systems.com>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "persons-model-contact-item.h"
#include <KIcon>
#include <KDebug>
#include <Nepomuk/Vocabulary/NCO>
#include <Soprano/Vocabulary/NAO>
#include <Soprano/Model>
#include <Soprano/QueryResultIterator>
#include <Nepomuk/Resource>
#include <Nepomuk/Variant>
#include <Nepomuk/ResourceManager>

class PersonsModelContactItemPrivate {
public:
    QHash<QUrl, QVariant> data;
};

PersonsModelContactItem::PersonsModelContactItem(const QUrl& uri, const QString& displayName)
    : d_ptr(new PersonsModelContactItemPrivate)
{
    setData(uri, PersonsModel::UriRole);
    setText(displayName);

    refreshIcon();
}

PersonsModelContactItem::~PersonsModelContactItem()
{
    delete d_ptr;
}

QMap<PersonsModel::ContactType, QIcon> initializeTypeIcons()
{
    QMap<PersonsModel::ContactType, QIcon> ret;
    ret.insert(PersonsModel::Email, QIcon::fromTheme(QLatin1String("mail-mark-unread")));
    ret.insert(PersonsModel::IM, QIcon::fromTheme(QLatin1String("im-user")));
    ret.insert(PersonsModel::Phone, QIcon::fromTheme(QLatin1String("phone")));
    ret.insert(PersonsModel::MobilePhone, QIcon::fromTheme(QLatin1String("phone")));
    ret.insert(PersonsModel::Postal, QIcon::fromTheme(QLatin1String("mail-message")));
    return ret;
}

static QMap<PersonsModel::ContactType, QIcon> s_contactTypeMap = initializeTypeIcons();

void PersonsModelContactItem::refreshIcon()
{
    PersonsModel::ContactType type = (PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt();
    setIcon(s_contactTypeMap[type]);
}

void PersonsModelContactItem::addData(const QUrl &key, const QVariant &value)
{
    if(value.isNull())
        return;

    if(Nepomuk::Vocabulary::NCO::imNickname() == key) {
        setText(value.toString());
    } else if (Nepomuk::Vocabulary::NCO::imID() == key) {
        setType(PersonsModel::IM);
    } else if (Nepomuk::Vocabulary::NCO::hasEmailAddress() == key) {
        setType(PersonsModel::Email);
    }else if (Nepomuk::Vocabulary::NCO::emailAddress() == key) {
        setText(value.toString());
    }

    Q_D(PersonsModelContactItem);
//     kDebug() << "Inserting" << value << "(" << key << ")";
    d->data.insert(key, value);
    emitDataChanged();
}

QVariant PersonsModelContactItem::dataValue(const QUrl &key)
{
    Q_D(PersonsModelContactItem);
    return d->data.value(key);
}

QUrl PersonsModelContactItem::uri() const
{
    return data(PersonsModel::UriRole).toUrl();
}

void PersonsModelContactItem::setType (PersonsModel::ContactType type)
{
    setData(type, PersonsModel::ContactTypeRole);
    refreshIcon();
}

QVariant PersonsModelContactItem::data(int role) const
{
    Q_D(const PersonsModelContactItem);
    switch(role) {
        case PersonsModel::NickRole: return d->data.value(Nepomuk::Vocabulary::NCO::imNickname());
        case PersonsModel::PhoneRole: return d->data.value(Nepomuk::Vocabulary::NCO::phoneNumber());
        case PersonsModel::EmailRole: return d->data.value(Nepomuk::Vocabulary::NCO::emailAddress());
        case PersonsModel::IMRole: return d->data.value(Nepomuk::Vocabulary::NCO::imID());
        case PersonsModel::PhotoRole: {
            QHash<QUrl, QVariant>::const_iterator it = d->data.constFind(Nepomuk::Vocabulary::NCO::photo());
            if(it==d->data.constEnd()) {
                const QString query = QString::fromLatin1("select ?url where { %1 nco:photo ?phRes. ?phRes nie:url ?url . }")
                                                          .arg( Soprano::Node::resourceToN3(uri()) );
                Soprano::Model* model = Nepomuk::ResourceManager::instance()->mainModel();
                Soprano::QueryResultIterator qit = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );

                QUrl url;
                if( qit.next() ) {
                    url = qit["url"].uri();
                }
                it = d_ptr->data.insert(Nepomuk::Vocabulary::NCO::photo(), url);
            }
            return it!=d->data.constEnd() ? it.value() : QVariant();
        }
        case PersonsModel::ContactIdRole: {
            int role = -1;
            switch((PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt()) {
                case PersonsModel::IM: role = PersonsModel::IMRole; break;
                case PersonsModel::Phone: role = PersonsModel::PhoneRole; break;
                case PersonsModel::Email: role = PersonsModel::EmailRole; break;
                case PersonsModel::MobilePhone: role = PersonsModel::PhoneRole; break;
                case PersonsModel::Postal: role = -1; break;
            }
            if(role>=0)
                return data(role);
        }   break;
    }
    return QStandardItem::data(role);
}
<|endoftext|>