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

#include "formatclipboard.hxx"

#ifndef _E3D_GLOBL3D_HXX
#include <svx/globl3d.hxx>
#endif

// header for class SfxItemIter
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif

// header for class SfxStyleSheet
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif

/*--------------------------------------------------------------------
 --------------------------------------------------------------------*/

SdFormatClipboard::SdFormatClipboard()
        : m_pItemSet(0)
        , m_bPersistentCopy(false)
        , m_nType_Inventor(0)
        , m_nType_Identifier(0)
{
}
SdFormatClipboard::~SdFormatClipboard()
{
    if(m_pItemSet)
        delete m_pItemSet;
}

bool SdFormatClipboard::HasContent() const
{
    return m_pItemSet!=0;
}

bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor )
        return false;
    switch(nObjectIdentifier)
    {
        case OBJ_NONE:
        case OBJ_GRUP:
            return false;
            break;
        case OBJ_LINE:
        case OBJ_RECT:
        case OBJ_CIRC:
        case OBJ_SECT:
        case OBJ_CARC:
        case OBJ_CCUT:
        case OBJ_POLY:
        case OBJ_PLIN:
        case OBJ_PATHLINE:
        case OBJ_PATHFILL:
        case OBJ_FREELINE:
        case OBJ_FREEFILL:
        case OBJ_SPLNLINE:
        case OBJ_SPLNFILL:
        case OBJ_TEXT:
        case OBJ_TEXTEXT:
        case OBJ_TITLETEXT:
            return true;
            break;
        case OBJ_OUTLINETEXT:
        case OBJ_GRAF:
        case OBJ_OLE2:
        case OBJ_EDGE:
        case OBJ_CAPTION:
            return false;
            break;
        case OBJ_PATHPOLY:
        case OBJ_PATHPLIN:
            return true;
            break;
        case OBJ_PAGE:
        case OBJ_MEASURE:
        case OBJ_DUMMY:
        case OBJ_FRAME:
        case OBJ_UNO:
        case OBJ_CUSTOMSHAPE:
            return false;
            break;
        default:
            return false;
            break;
    }
    return true;
}

bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( !HasContent() )
        return false;
    if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) )
        return false;
    return true;
}

void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy )
{
    this->Erase();
    m_bPersistentCopy = bPersistentCopy;

    const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
    if( rMarkList.GetMarkCount() >= 1 )
    {
        BOOL bOnlyHardAttr = FALSE;
        m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) );

        SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
        m_nType_Inventor = pObj->GetObjInventor();
        m_nType_Identifier = pObj->GetObjIdentifier();
    }
}

void SdFormatClipboard::Paste( ::sd::View& rDrawView
                              , bool bNoCharacterFormats, bool bNoParagraphFormats )
{
    if( !rDrawView.AreObjectsMarked() )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }

    SdrObject* pObj = 0;

    bool bWrongTargetType = false;
    {
        const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
        if( rMarkList.GetMarkCount() != 1 )
            bWrongTargetType = true;
        else
        {
            pObj = rMarkList.GetMark(0)->GetObj();
            if( pObj && pObj->GetStyleSheet() )
                bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() );
        }
    }
    if( bWrongTargetType )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }
    if(m_pItemSet)
    {
        //modify source itemset
        {
            BOOL bOnlyHardAttr = FALSE;
            SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() );

            USHORT nWhich=0;
            SfxItemState nSourceState;
            SfxItemState nTargetState;
            const SfxPoolItem* pSourceItem=0;
            const SfxPoolItem* pTargetItem=0;
            SfxItemIter aSourceIter(*m_pItemSet);
            pSourceItem = aSourceIter.FirstItem();
            while( pSourceItem!=NULL )
            {
                if (!IsInvalidItem(pSourceItem))
                {
                    nWhich = pSourceItem->Which();
                    if(nWhich)
                    {
                        nSourceState = m_pItemSet->GetItemState( nWhich );
                        nTargetState = aTargetSet.GetItemState( nWhich );
                        pTargetItem = aTargetSet.GetItem( nWhich );
                        ::com::sun::star::uno::Any aSourceValue, aTargetValue;

                        if(!pTargetItem)
                            m_pItemSet->ClearItem(nWhich);
                        else if( (*pSourceItem) == (*pTargetItem) )
                        {
                            //do not set items which have the same content in source and target
                            m_pItemSet->ClearItem(nWhich);
                        }
                    }
                }
                pSourceItem = aSourceIter.NextItem();
            }//end while
        }
        BOOL bReplaceAll = TRUE;
        rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll);
    }
    if(!m_bPersistentCopy)
        this->Erase();
}

void SdFormatClipboard::Erase()
{
    if(m_pItemSet)
    {
        delete m_pItemSet;
        m_pItemSet = 0;
    }
    m_nType_Inventor=0;
    m_nType_Identifier=0;
    m_bPersistentCopy = false;
}
<commit_msg>INTEGRATION: CWS sch05 (1.3.112); FILE MERGED 2004/11/25 14:18:11 iha 1.3.112.1: #i37758# formatpaintbrush didn't not work with custom shapes<commit_after>/*************************************************************************
 *
 *  $RCSfile: formatclipboard.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-12-10 17:22:43 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2004 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "formatclipboard.hxx"

#ifndef _E3D_GLOBL3D_HXX
#include <svx/globl3d.hxx>
#endif

// header for class SfxItemIter
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif

// header for class SfxStyleSheet
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif

/*--------------------------------------------------------------------
 --------------------------------------------------------------------*/

SdFormatClipboard::SdFormatClipboard()
        : m_pItemSet(0)
        , m_bPersistentCopy(false)
        , m_nType_Inventor(0)
        , m_nType_Identifier(0)
{
}
SdFormatClipboard::~SdFormatClipboard()
{
    if(m_pItemSet)
        delete m_pItemSet;
}

bool SdFormatClipboard::HasContent() const
{
    return m_pItemSet!=0;
}

bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor )
        return false;
    switch(nObjectIdentifier)
    {
        case OBJ_NONE:
        case OBJ_GRUP:
            return false;
            break;
        case OBJ_LINE:
        case OBJ_RECT:
        case OBJ_CIRC:
        case OBJ_SECT:
        case OBJ_CARC:
        case OBJ_CCUT:
        case OBJ_POLY:
        case OBJ_PLIN:
        case OBJ_PATHLINE:
        case OBJ_PATHFILL:
        case OBJ_FREELINE:
        case OBJ_FREEFILL:
        case OBJ_SPLNLINE:
        case OBJ_SPLNFILL:
        case OBJ_TEXT:
        case OBJ_TEXTEXT:
        case OBJ_TITLETEXT:
            return true;
            break;
        case OBJ_OUTLINETEXT:
        case OBJ_GRAF:
        case OBJ_OLE2:
        case OBJ_EDGE:
        case OBJ_CAPTION:
            return false;
            break;
        case OBJ_PATHPOLY:
        case OBJ_PATHPLIN:
            return true;
            break;
        case OBJ_PAGE:
        case OBJ_MEASURE:
        case OBJ_DUMMY:
        case OBJ_FRAME:
        case OBJ_UNO:
            return false;
            break;
        case OBJ_CUSTOMSHAPE:
            return true;
            break;
        default:
            return false;
            break;
    }
    return true;
}

bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( !HasContent() )
        return false;
    if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) )
        return false;
    return true;
}

void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy )
{
    this->Erase();
    m_bPersistentCopy = bPersistentCopy;

    const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
    if( rMarkList.GetMarkCount() >= 1 )
    {
        BOOL bOnlyHardAttr = FALSE;
        m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) );

        SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
        m_nType_Inventor = pObj->GetObjInventor();
        m_nType_Identifier = pObj->GetObjIdentifier();
    }
}

void SdFormatClipboard::Paste( ::sd::View& rDrawView
                              , bool bNoCharacterFormats, bool bNoParagraphFormats )
{
    if( !rDrawView.AreObjectsMarked() )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }

    SdrObject* pObj = 0;

    bool bWrongTargetType = false;
    {
        const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
        if( rMarkList.GetMarkCount() != 1 )
            bWrongTargetType = true;
        else
        {
            pObj = rMarkList.GetMark(0)->GetObj();
            if( pObj && pObj->GetStyleSheet() )
                bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() );
        }
    }
    if( bWrongTargetType )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }
    if(m_pItemSet)
    {
        //modify source itemset
        {
            BOOL bOnlyHardAttr = FALSE;
            SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() );

            USHORT nWhich=0;
            SfxItemState nSourceState;
            SfxItemState nTargetState;
            const SfxPoolItem* pSourceItem=0;
            const SfxPoolItem* pTargetItem=0;
            SfxItemIter aSourceIter(*m_pItemSet);
            pSourceItem = aSourceIter.FirstItem();
            while( pSourceItem!=NULL )
            {
                if (!IsInvalidItem(pSourceItem))
                {
                    nWhich = pSourceItem->Which();
                    if(nWhich)
                    {
                        nSourceState = m_pItemSet->GetItemState( nWhich );
                        nTargetState = aTargetSet.GetItemState( nWhich );
                        pTargetItem = aTargetSet.GetItem( nWhich );
                        ::com::sun::star::uno::Any aSourceValue, aTargetValue;

                        if(!pTargetItem)
                            m_pItemSet->ClearItem(nWhich);
                        else if( (*pSourceItem) == (*pTargetItem) )
                        {
                            //do not set items which have the same content in source and target
                            m_pItemSet->ClearItem(nWhich);
                        }
                    }
                }
                pSourceItem = aSourceIter.NextItem();
            }//end while
        }
        BOOL bReplaceAll = TRUE;
        rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll);
    }
    if(!m_bPersistentCopy)
        this->Erase();
}

void SdFormatClipboard::Erase()
{
    if(m_pItemSet)
    {
        delete m_pItemSet;
        m_pItemSet = 0;
    }
    m_nType_Inventor=0;
    m_nType_Identifier=0;
    m_bPersistentCopy = false;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLExportDDELinks.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2004-03-08 11:53:09 $
 *
 *  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 PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#ifndef _SC_XMLEXPORTDDELINKS_HXX
#include "XMLExportDDELinks.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif

#ifndef SC_XMLEXPRT_HXX
#include "xmlexprt.hxx"
#endif
#ifndef SC_UNONAMES_HXX
#include "unonames.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_MATRIX_HXX
#include "scmatrix.hxx"
#endif

#ifndef _COM_SUN_STAR_SHEET_XDDELINK_HPP_
#include <com/sun/star/sheet/XDDELink.hpp>
#endif

class ScMatrix;

using namespace com::sun::star;
using namespace xmloff::token;

ScXMLExportDDELinks::ScXMLExportDDELinks(ScXMLExport& rTempExport)
    : rExport(rTempExport)
{
}

ScXMLExportDDELinks::~ScXMLExportDDELinks()
{
}

sal_Bool ScXMLExportDDELinks::CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue,
                     const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue)
{
    if (bEmpty == bPrevEmpty)
        if (bEmpty)
            return sal_True;
        else if (bString == bPrevString)
            if (bString)
                return (sPrevValue == sValue);
            else
                return (fPrevValue == fValue);
        else
            return sal_False;
    else
        return sal_False;
}

void ScXMLExportDDELinks::WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat)
{
    rtl::OUStringBuffer sBuffer;
    if (!bEmpty)
        if (bString)
        {
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE_TYPE, XML_STRING);
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_STRING_VALUE, rtl::OUString(sValue));
        }
        else
        {
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE_TYPE, XML_FLOAT);
            rExport.GetMM100UnitConverter().convertDouble(sBuffer, fValue);
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE, sBuffer.makeStringAndClear());
        }
    if (nRepeat > 1)
    {
        rExport.GetMM100UnitConverter().convertNumber(sBuffer, nRepeat);
        rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear());
    }
    SvXMLElementExport(rExport, XML_NAMESPACE_TABLE, XML_TABLE_CELL, sal_True, sal_True);
}

void ScXMLExportDDELinks::WriteTable(const sal_Int32 nPos)
{
    const ScMatrix* pMatrix = NULL;
    if (rExport.GetDocument())
        pMatrix = rExport.GetDocument()->GetDdeLinkResultMatrix( static_cast<USHORT>(nPos) );
    if (pMatrix)
    {
        USHORT nuCol, nuRow;
        pMatrix->GetDimensions( nuCol, nuRow );
        sal_Int32 nRowCount = nuRow;
        sal_Int32 nColCount = nuCol;
        SvXMLElementExport aTableElem(rExport, XML_NAMESPACE_TABLE, XML_TABLE, sal_True, sal_True);
        rtl::OUStringBuffer sBuffer;
        if (nColCount > 1)
        {
            rExport.GetMM100UnitConverter().convertNumber(sBuffer, nColCount);
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear());
        }
        {
            SvXMLElementExport aElemCol(rExport, XML_NAMESPACE_TABLE, XML_TABLE_COLUMN, sal_True, sal_True);
        }
        sal_Bool bPrevString(sal_True);
        sal_Bool bPrevEmpty(sal_True);
        double fPrevValue;
        String sPrevValue;
        sal_Int32 nRepeatColsCount(1);
        for(sal_Int32 nRow = 0; nRow < nRowCount; nRow++)
        {
            SvXMLElementExport aElemRow(rExport, XML_NAMESPACE_TABLE, XML_TABLE_ROW, sal_True, sal_True);
            for(sal_Int32 nColumn = 0; nColumn < nColCount; nColumn++)
            {
                BOOL bIsString = FALSE;
                const MatValue* pMatVal = pMatrix->Get( static_cast<USHORT>(nColumn), static_cast<USHORT>(nRow), bIsString );

                if (nColumn == 0)
                {
                    bPrevEmpty = !pMatVal;
                    bPrevString = bIsString;
                    if( bIsString )
                        sPrevValue = pMatVal->GetString();
                    else
                        fPrevValue = pMatVal->fVal;
                }
                else
                {
                    double fValue;
                    String sValue;
                    sal_Bool bEmpty = !pMatVal;
                    sal_Bool bString = bIsString;
                    if( bIsString )
                        sValue = pMatVal->GetString();
                    else
                        fValue = pMatVal->fVal;

                    if (CellsEqual(bPrevEmpty, bPrevString, sPrevValue, fPrevValue,
                                bEmpty, bString, sValue, fValue))
                        nRepeatColsCount++;
                    else
                    {
                        WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount);
                        nRepeatColsCount = 1;
                        bPrevEmpty = bEmpty;
                        fPrevValue = fValue;
                        sPrevValue = sValue;
                    }
                }
            }
            WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount);
            nRepeatColsCount = 1;
        }
    }
}

void ScXMLExportDDELinks::WriteDDELinks(uno::Reference<sheet::XSpreadsheetDocument>& xSpreadDoc)
{
    uno::Reference <beans::XPropertySet> xPropertySet (xSpreadDoc, uno::UNO_QUERY);
    if (xPropertySet.is())
    {
        uno::Any aDDELinks = xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DDELINKS)));
        uno::Reference<container::XIndexAccess> xIndex;
        if (aDDELinks >>= xIndex)
        {
            sal_Int32 nCount = xIndex->getCount();
            if (nCount)
            {
                SvXMLElementExport aElemDDEs(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINKS, sal_True, sal_True);
                for (sal_uInt16 nDDELink = 0; nDDELink < nCount; nDDELink++)
                {
                    uno::Any aDDELink = xIndex->getByIndex(nDDELink);
                    uno::Reference<sheet::XDDELink> xDDELink;
                    if (aDDELink >>= xDDELink)
                    {
                        SvXMLElementExport aElemDDE(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINK, sal_True, sal_True);
                        {
                            rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_APPLICATION, xDDELink->getApplication());
                            rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_TOPIC, xDDELink->getTopic());
                            rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_ITEM, xDDELink->getItem());
                            rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_AUTOMATIC_UPDATE, XML_TRUE);
                            BYTE nMode;
                            if (rExport.GetDocument() &&
                                rExport.GetDocument()->GetDdeLinkMode(nDDELink, nMode))
                            {
                                switch (nMode)
                                {
                                    case SC_DDE_ENGLISH :
                                        rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_INTO_ENGLISH_NUMBER);
                                    case SC_DDE_TEXT :
                                        rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_LET_TEXT);
                                }
                            }
                            SvXMLElementExport(rExport, XML_NAMESPACE_OFFICE, XML_DDE_SOURCE, sal_True, sal_True);
                        }
                        WriteTable(nDDELink);
                    }
                }
            }
        }
    }
}
<commit_msg>INTEGRATION: CWS rowlimit (1.8.324); FILE MERGED 2004/03/17 12:24:59 er 1.8.324.3: #i1967# type correctness (ScMatrix parameters are SCSIZE now) 2004/03/15 17:24:10 er 1.8.324.2: RESYNC: (1.8-1.9); FILE MERGED 2004/01/19 19:09:23 jmarmion 1.8.324.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short.<commit_after>/*************************************************************************
 *
 *  $RCSfile: XMLExportDDELinks.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:09:20 $
 *
 *  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 PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#ifndef _SC_XMLEXPORTDDELINKS_HXX
#include "XMLExportDDELinks.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif

#ifndef SC_XMLEXPRT_HXX
#include "xmlexprt.hxx"
#endif
#ifndef SC_UNONAMES_HXX
#include "unonames.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_MATRIX_HXX
#include "scmatrix.hxx"
#endif

#ifndef _COM_SUN_STAR_SHEET_XDDELINK_HPP_
#include <com/sun/star/sheet/XDDELink.hpp>
#endif

class ScMatrix;

using namespace com::sun::star;
using namespace xmloff::token;

ScXMLExportDDELinks::ScXMLExportDDELinks(ScXMLExport& rTempExport)
    : rExport(rTempExport)
{
}

ScXMLExportDDELinks::~ScXMLExportDDELinks()
{
}

sal_Bool ScXMLExportDDELinks::CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue,
                     const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue)
{
    if (bEmpty == bPrevEmpty)
        if (bEmpty)
            return sal_True;
        else if (bString == bPrevString)
            if (bString)
                return (sPrevValue == sValue);
            else
                return (fPrevValue == fValue);
        else
            return sal_False;
    else
        return sal_False;
}

void ScXMLExportDDELinks::WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat)
{
    rtl::OUStringBuffer sBuffer;
    if (!bEmpty)
        if (bString)
        {
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE_TYPE, XML_STRING);
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_STRING_VALUE, rtl::OUString(sValue));
        }
        else
        {
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE_TYPE, XML_FLOAT);
            rExport.GetMM100UnitConverter().convertDouble(sBuffer, fValue);
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_VALUE, sBuffer.makeStringAndClear());
        }
    if (nRepeat > 1)
    {
        rExport.GetMM100UnitConverter().convertNumber(sBuffer, nRepeat);
        rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear());
    }
    SvXMLElementExport(rExport, XML_NAMESPACE_TABLE, XML_TABLE_CELL, sal_True, sal_True);
}

void ScXMLExportDDELinks::WriteTable(const sal_Int32 nPos)
{
    const ScMatrix* pMatrix = NULL;
    if (rExport.GetDocument())
        pMatrix = rExport.GetDocument()->GetDdeLinkResultMatrix( static_cast<USHORT>(nPos) );
    if (pMatrix)
    {
        SCSIZE nuCol;
        SCSIZE nuRow;
        pMatrix->GetDimensions( nuCol, nuRow );
        sal_Int32 nRowCount = static_cast<sal_Int32>(nuRow);
        sal_Int32 nColCount = static_cast<sal_Int32>(nuCol);
        SvXMLElementExport aTableElem(rExport, XML_NAMESPACE_TABLE, XML_TABLE, sal_True, sal_True);
        rtl::OUStringBuffer sBuffer;
        if (nColCount > 1)
        {
            rExport.GetMM100UnitConverter().convertNumber(sBuffer, nColCount);
            rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_NUMBER_COLUMNS_REPEATED, sBuffer.makeStringAndClear());
        }
        {
            SvXMLElementExport aElemCol(rExport, XML_NAMESPACE_TABLE, XML_TABLE_COLUMN, sal_True, sal_True);
        }
        sal_Bool bPrevString(sal_True);
        sal_Bool bPrevEmpty(sal_True);
        double fPrevValue;
        String sPrevValue;
        sal_Int32 nRepeatColsCount(1);
        for(sal_Int32 nRow = 0; nRow < nRowCount; nRow++)
        {
            SvXMLElementExport aElemRow(rExport, XML_NAMESPACE_TABLE, XML_TABLE_ROW, sal_True, sal_True);
            for(sal_Int32 nColumn = 0; nColumn < nColCount; nColumn++)
            {
                BOOL bIsString = FALSE;
                const MatValue* pMatVal = pMatrix->Get( static_cast<SCSIZE>(nColumn), static_cast<SCSIZE>(nRow), bIsString );

                if (nColumn == 0)
                {
                    bPrevEmpty = !pMatVal;
                    bPrevString = bIsString;
                    if( bIsString )
                        sPrevValue = pMatVal->GetString();
                    else
                        fPrevValue = pMatVal->fVal;
                }
                else
                {
                    double fValue;
                    String sValue;
                    sal_Bool bEmpty = !pMatVal;
                    sal_Bool bString = bIsString;
                    if( bIsString )
                        sValue = pMatVal->GetString();
                    else
                        fValue = pMatVal->fVal;

                    if (CellsEqual(bPrevEmpty, bPrevString, sPrevValue, fPrevValue,
                                bEmpty, bString, sValue, fValue))
                        nRepeatColsCount++;
                    else
                    {
                        WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount);
                        nRepeatColsCount = 1;
                        bPrevEmpty = bEmpty;
                        fPrevValue = fValue;
                        sPrevValue = sValue;
                    }
                }
            }
            WriteCell(bPrevEmpty, bPrevString, sPrevValue, fPrevValue, nRepeatColsCount);
            nRepeatColsCount = 1;
        }
    }
}

void ScXMLExportDDELinks::WriteDDELinks(uno::Reference<sheet::XSpreadsheetDocument>& xSpreadDoc)
{
    uno::Reference <beans::XPropertySet> xPropertySet (xSpreadDoc, uno::UNO_QUERY);
    if (xPropertySet.is())
    {
        uno::Any aDDELinks = xPropertySet->getPropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(SC_UNO_DDELINKS)));
        uno::Reference<container::XIndexAccess> xIndex;
        if (aDDELinks >>= xIndex)
        {
            sal_Int32 nCount = xIndex->getCount();
            if (nCount)
            {
                SvXMLElementExport aElemDDEs(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINKS, sal_True, sal_True);
                for (sal_uInt16 nDDELink = 0; nDDELink < nCount; nDDELink++)
                {
                    uno::Any aDDELink = xIndex->getByIndex(nDDELink);
                    uno::Reference<sheet::XDDELink> xDDELink;
                    if (aDDELink >>= xDDELink)
                    {
                        SvXMLElementExport aElemDDE(rExport, XML_NAMESPACE_TABLE, XML_DDE_LINK, sal_True, sal_True);
                        {
                            rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_APPLICATION, xDDELink->getApplication());
                            rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_TOPIC, xDDELink->getTopic());
                            rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_DDE_ITEM, xDDELink->getItem());
                            rExport.AddAttribute(XML_NAMESPACE_OFFICE, XML_AUTOMATIC_UPDATE, XML_TRUE);
                            BYTE nMode;
                            if (rExport.GetDocument() &&
                                rExport.GetDocument()->GetDdeLinkMode(nDDELink, nMode))
                            {
                                switch (nMode)
                                {
                                    case SC_DDE_ENGLISH :
                                        rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_INTO_ENGLISH_NUMBER);
                                    case SC_DDE_TEXT :
                                        rExport.AddAttribute(XML_NAMESPACE_TABLE, XML_CONVERSION_MODE, XML_LET_TEXT);
                                }
                            }
                            SvXMLElementExport(rExport, XML_NAMESPACE_OFFICE, XML_DDE_SOURCE, sal_True, sal_True);
                        }
                        WriteTable(nDDELink);
                    }
                }
            }
        }
    }
}
<|endoftext|>


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

#ifndef _SC_XMLEXPORTDDELINKS_HXX
#define _SC_XMLEXPORTDDELINKS_HXX

#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#endif

class String;
class ScXMLExport;

class ScXMLExportDDELinks
{
    ScXMLExport&        rExport;

    sal_Bool            CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue,
                                    const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue);
    void                WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat);
    void                WriteTable(const sal_Int32 nPos);
public:
    ScXMLExportDDELinks(ScXMLExport& rExport);
    ~ScXMLExportDDELinks();
    void WriteDDELinks(::com::sun::star::uno::Reference < ::com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc);
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.5.700); FILE MERGED 2008/04/01 12:36:30 thb 1.5.700.2: #i85898# Stripping all external header guards 2008/03/31 17:14:55 rt 1.5.700.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: XMLExportDDELinks.hxx,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.
 *
 ************************************************************************/

#ifndef _SC_XMLEXPORTDDELINKS_HXX
#define _SC_XMLEXPORTDDELINKS_HXX

#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>

class String;
class ScXMLExport;

class ScXMLExportDDELinks
{
    ScXMLExport&        rExport;

    sal_Bool            CellsEqual(const sal_Bool bPrevEmpty, const sal_Bool bPrevString, const String& sPrevValue, const double& fPrevValue,
                                    const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue);
    void                WriteCell(const sal_Bool bEmpty, const sal_Bool bString, const String& sValue, const double& fValue, const sal_Int32 nRepeat);
    void                WriteTable(const sal_Int32 nPos);
public:
    ScXMLExportDDELinks(ScXMLExport& rExport);
    ~ScXMLExportDDELinks();
    void WriteDDELinks(::com::sun::star::uno::Reference < ::com::sun::star::sheet::XSpreadsheetDocument >& xSpreadDoc);
};

#endif

<|endoftext|>


<commit_before>//   /$$$$$$$  /$$$$$$$$  /$$$$$$  /$$$$$$  /$$$$$$  /$$$$$$$$ /$$$$$$  /$$$$$$$
//  | $$__  $$| $$_____/ /$$__  $$|_  $$_/ /$$__  $$|__  $$__//$$__  $$| $$__  $$
//  | $$  \ $$| $$      | $$  \__/  | $$  | $$  \__/   | $$  | $$  \ $$| $$  \ $$
//  | $$$$$$$/| $$$$$   |  $$$$$$   | $$  |  $$$$$$    | $$  | $$  | $$| $$$$$$$/
//  | $$__  $$| $$__/    \____  $$  | $$   \____  $$   | $$  | $$  | $$| $$__  $$
//  | $$  \ $$| $$       /$$  \ $$  | $$   /$$  \ $$   | $$  | $$  | $$| $$  \ $$
//  | $$  | $$| $$$$$$$$|  $$$$$$/ /$$$$$$|  $$$$$$/   | $$  |  $$$$$$/| $$  | $$
//  |__/  |__/|________/ \______/ |______/ \______/    |__/   \______/ |__/  |__/

#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <exception>
#include <bitset>
#include <stdlib.h>

// Bitwise operations for extracting data from return stream
#define S1(k,n) ((k) & ((1<<(n))-1))
#define F10(k,m,n) S1((k)>>(m),((n)-(m)))

// Set global serial port handle
HANDLE Resipod;
DCB ResipodParam = { 0 };

// Not C++ recommended to make this global, but I am lazy
// and don't want to figure out how to return a byte array
byte receive[] = { 0x0,0x0,0x0 };

void GetResistance() {
	byte command[] = { 0xC1,0xD2,0x21 };
	DWORD bytesWrite = 0;
	DWORD bytesRead = 0;
	WriteFile(Resipod, command, 3, &bytesWrite, NULL);
	ReadFile(Resipod, receive, 3, &bytesRead, NULL);
	if (receive[0] != 0x02) {
		std::cout << "Received value does not contain correct start byte. Non-fatal error.\n";
	}
}

int InitializePort() {
	int userComPort = 3;
	std::cout << "Enter COM port number that Resipod is connected to: ";
	std::cin >> userComPort;
	std::wstringstream comPort;
	comPort << "\\\\.\\COM" << userComPort;

	std::cout << "\nChecking port COM" << userComPort << "...";

	Resipod = CreateFile(comPort.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	if (Resipod == INVALID_HANDLE_VALUE) {
		DWORD dwError = GetLastError();
		if (dwError == ERROR_ACCESS_DENIED || dwError == ERROR_GEN_FAILURE || dwError == ERROR_SHARING_VIOLATION || dwError == ERROR_SEM_TIMEOUT) {
			std::cout << "resource in use and not usable\n";
		}
		else {
			std::cout << "error opening port\n";
		}
		return(0);
	}
	else {
		std::cout << "success!\n";
		ResipodParam.DCBlength = sizeof(ResipodParam);

		// Hardcode serial parameters based on Resipod data

		ResipodParam.BaudRate = CBR_19200;
		ResipodParam.ByteSize = 8;
		ResipodParam.StopBits = 1;
		ResipodParam.Parity = NOPARITY;
		ResipodParam.fOutX = FALSE;
		ResipodParam.fInX = FALSE;
		ResipodParam.fTXContinueOnXoff = FALSE;
		SetCommState(Resipod, &ResipodParam);

		// Set some timeout values
		COMMTIMEOUTS timeouts = { 0 };
		timeouts.ReadIntervalTimeout = 200;
		timeouts.ReadTotalTimeoutConstant = 1000;
		timeouts.ReadTotalTimeoutMultiplier = 1;
		timeouts.WriteTotalTimeoutConstant = 200;
		timeouts.WriteTotalTimeoutMultiplier = 1;

		// Get ID on port to see if it is a Proceq device
		/*byte command[] = { 0xC1,0xD2,0x21 };
		byte getID[] = { 0x10,0x49,0x44,0x0D };
		char receiveID[8] = {0};
		char correctID[8] = "Resipod";
		DWORD bytesWriteID = 0;
		DWORD bytesReadID = 0;
		WriteFile(Resipod, command, 3, &bytesWriteID, NULL);
		ReadFile(Resipod, receiveID, 3, &bytesReadID, NULL);
		WriteFile(Resipod, getID, 5, &bytesWriteID, NULL);
		ReadFile(Resipod, receiveID, 8, &bytesReadID, NULL);
		if (SetCommTimeouts(Resipod, &timeouts) == 0) {
			std::cout << "timeout\n";
		}
		else {
			std::cout << receiveID << "\n";
			if (strcmp(receiveID, correctID)) {
				return(j);
			}
		}*/

	}

	return(userComPort);
}

void DisplayHeader() {
	std::cout << "   /$$$$$$$  /$$$$$$$$  /$$$$$$  /$$$$$$  /$$$$$$  /$$$$$$$$ /$$$$$$  /$$$$$$$\n";
	std::cout << "  | $$__  $$| $$_____/ /$$__  $$|_  $$_/ /$$__  $$|__  $$__//$$__  $$| $$__  $$\n";
	std::cout << "  | $$  \\ $$| $$      | $$  \\__/  | $$  | $$  \\__/   | $$  | $$  \\ $$| $$  \\ $$\n";
	std::cout << "  | $$$$$$$/| $$$$$   |  $$$$$$   | $$  |  $$$$$$    | $$  | $$  | $$| $$$$$$$/\n";
	std::cout << "  | $$__  $$| $$__/    \\____  $$  | $$   \\____  $$   | $$  | $$  | $$| $$__  $$\n";
	std::cout << "  | $$  \\ $$| $$       /$$  \\ $$  | $$   /$$  \\ $$   | $$  | $$  | $$| $$  \\ $$\n";
	std::cout << "  | $$  | $$| $$$$$$$$|  $$$$$$/ /$$$$$$|  $$$$$$/   | $$  |  $$$$$$/| $$  | $$\n";
	std::cout << "  |__/  |__/|________/ \\______/ |______/ \\______/    |__/   \\______/ |__/  |__/\n";
	std::cout << "\n\n    Current code is in testing phase. Do NOT use for research purposes...\n\n";
}

int main() {
	char TestInterface;
	char dummy;
	DisplayHeader();
	std::cout << "Initializing serial port interface...";
	int PortOpen = InitializePort();
	if (PortOpen = 0) {
		std::cout << "no Resipod device found!\n";
		std::cout << "Press any key to terminate program...";
		std::cin >> dummy;
		return(EXIT_FAILURE);
	}
	else {
		std::cout << "success!\n\n";
		std::cout << "Resipod device is on COM" << PortOpen << "\n";
	}
	std::cout << "Current test program will obtain three readings at an interval of 3 seconds.\n";
	std::cout << "Press any key when ready to test interface...";
	std::cin >> TestInterface;

	for (int i = 1; i < 4; i++) {
		std::cout << "\n\n\nStarting measurement #" << i << "...\n\n";
		GetResistance();
		std::cout << "  Checking first byte received\n";
		std::cout << "--------------------------------\n";
		std::cout << std::bitset<8>(0x02) << "  - expected from device\n";
		std::cout << std::bitset<8>(receive[0]) << "  - received from device\n";
		std::cout << "--------------------------------\n";
		if (receive[0] = 0x02) {
			std::cout << "Bytes match, next values should be correct.\n";
		}
		else {
			std::cout << "Bytes do not match! Next values unlikely to be correct!\n";
		}
		unsigned output1 = (receive[2] << 8) | (receive[1]);
		std::cout << std::bitset<16>(output1) << "\n";
		int reading = F10(output1, 0, 11);
		double resistance = reading;
		bool divide10 = F10(output1, 11, 12);
		if (divide10) {
			resistance = reading / 10.0;
		}

		std::cout << "Decimal number: " << reading << "\n";
		std::cout << "Binary number: " << std::bitset<16>(reading) << "\n";
		std::cout << "Resistance: " << resistance << " ohms\n\n\n";
		std::cin >> reading;
	}

}<commit_msg>First viable release version with user control<commit_after>//   /$$$$$$$  /$$$$$$$$  /$$$$$$  /$$$$$$  /$$$$$$  /$$$$$$$$ /$$$$$$  /$$$$$$$
//  | $$__  $$| $$_____/ /$$__  $$|_  $$_/ /$$__  $$|__  $$__//$$__  $$| $$__  $$
//  | $$  \ $$| $$      | $$  \__/  | $$  | $$  \__/   | $$  | $$  \ $$| $$  \ $$
//  | $$$$$$$/| $$$$$   |  $$$$$$   | $$  |  $$$$$$    | $$  | $$  | $$| $$$$$$$/
//  | $$__  $$| $$__/    \____  $$  | $$   \____  $$   | $$  | $$  | $$| $$__  $$
//  | $$  \ $$| $$       /$$  \ $$  | $$   /$$  \ $$   | $$  | $$  | $$| $$  \ $$
//  | $$  | $$| $$$$$$$$|  $$$$$$/ /$$$$$$|  $$$$$$/   | $$  |  $$$$$$/| $$  | $$
//  |__/  |__/|________/ \______/ |______/ \______/    |__/   \______/ |__/  |__/

#include <Windows.h>
#include <iostream>
#include <string>
#include <sstream>
#include <exception>
#include <bitset>
#include <stdlib.h>
#include <fstream>
#include <chrono>
#include <ctime>

// Bitwise operations for extracting data from return stream
#define S1(k,n) ((k) & ((1<<(n))-1))
#define F10(k,m,n) S1((k)>>(m),((n)-(m)))

// Set global serial port handle
HANDLE Resipod;
DCB ResipodParam = { 0 };

// Get timer ready
HANDLE timer = NULL;
LARGE_INTEGER timerValue;

double GetResistance() {
	byte command[] = { 0xC1,0xD2,0x21 };
	byte receive[] = { 0x0, 0x0, 0x0 };
	DWORD bytesWrite = 0;
	DWORD bytesRead = 0;
	WriteFile(Resipod, command, 3, &bytesWrite, NULL);
	ReadFile(Resipod, receive, 3, &bytesRead, NULL);
	if (receive[0] != 0x02) {
		return(-1.0);
	}

	unsigned output1 = (receive[2] << 8) | (receive[1]);
	int reading = F10(output1, 0, 11);
	double resistance = reading;
	bool divide10 = F10(output1, 11, 12);
	if (divide10) {
		resistance = reading / 10.0;
	}

	return(resistance);
}

int InitializePort() {
	int userComPort = 3;
	std::cout << "Enter COM port number that Resipod is connected to: ";
	std::cin >> userComPort;
	std::wstringstream comPort;
	comPort << "\\\\.\\COM" << userComPort;

	std::cout << "\nChecking port COM" << userComPort << "...";

	Resipod = CreateFile(comPort.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
	if (Resipod == INVALID_HANDLE_VALUE) {
		DWORD dwError = GetLastError();
		if (dwError == ERROR_ACCESS_DENIED || dwError == ERROR_GEN_FAILURE || dwError == ERROR_SHARING_VIOLATION || dwError == ERROR_SEM_TIMEOUT) {
			std::cout << "resource in use and not usable\n";
		}
		else {
			std::cout << "error opening port\n";
		}
		return(0);
	}
	else {
		std::cout << "success!\n";
		ResipodParam.DCBlength = sizeof(ResipodParam);

		// Hardcode serial parameters based on Resipod data

		ResipodParam.BaudRate = CBR_19200;
		ResipodParam.ByteSize = 8;
		ResipodParam.StopBits = 1;
		ResipodParam.Parity = NOPARITY;
		ResipodParam.fOutX = FALSE;
		ResipodParam.fInX = FALSE;
		ResipodParam.fTXContinueOnXoff = FALSE;
		SetCommState(Resipod, &ResipodParam);

		// Set some timeout values
		COMMTIMEOUTS timeouts = { 0 };
		timeouts.ReadIntervalTimeout = 200;
		timeouts.ReadTotalTimeoutConstant = 1000;
		timeouts.ReadTotalTimeoutMultiplier = 1;
		timeouts.WriteTotalTimeoutConstant = 200;
		timeouts.WriteTotalTimeoutMultiplier = 1;

		// Get ID on port to see if it is a Proceq device
		/*byte command[] = { 0xC1,0xD2,0x21 };
		byte getID[] = { 0x10,0x49,0x44,0x0D };
		char receiveID[8] = {0};
		char correctID[8] = "Resipod";
		DWORD bytesWriteID = 0;
		DWORD bytesReadID = 0;
		WriteFile(Resipod, command, 3, &bytesWriteID, NULL);
		ReadFile(Resipod, receiveID, 3, &bytesReadID, NULL);
		WriteFile(Resipod, getID, 5, &bytesWriteID, NULL);
		ReadFile(Resipod, receiveID, 8, &bytesReadID, NULL);
		if (SetCommTimeouts(Resipod, &timeouts) == 0) {
			std::cout << "timeout\n";
		}
		else {
			std::cout << receiveID << "\n";
			if (strcmp(receiveID, correctID)) {
				return(j);
			}
		}*/

	}

	return(userComPort);
}

void DisplayHeader() {
	std::cout << "   /$$$$$$$  /$$$$$$$$  /$$$$$$  /$$$$$$  /$$$$$$  /$$$$$$$$ /$$$$$$  /$$$$$$$\n";
	std::cout << "  | $$__  $$| $$_____/ /$$__  $$|_  $$_/ /$$__  $$|__  $$__//$$__  $$| $$__  $$\n";
	std::cout << "  | $$  \\ $$| $$      | $$  \\__/  | $$  | $$  \\__/   | $$  | $$  \\ $$| $$  \\ $$\n";
	std::cout << "  | $$$$$$$/| $$$$$   |  $$$$$$   | $$  |  $$$$$$    | $$  | $$  | $$| $$$$$$$/\n";
	std::cout << "  | $$__  $$| $$__/    \\____  $$  | $$   \\____  $$   | $$  | $$  | $$| $$__  $$\n";
	std::cout << "  | $$  \\ $$| $$       /$$  \\ $$  | $$   /$$  \\ $$   | $$  | $$  | $$| $$  \\ $$\n";
	std::cout << "  | $$  | $$| $$$$$$$$|  $$$$$$/ /$$$$$$|  $$$$$$/   | $$  |  $$$$$$/| $$  | $$\n";
	std::cout << "  |__/  |__/|________/ \\______/ |______/ \\______/    |__/   \\______/ |__/  |__/\n";
	//std::cout << "\n\n    Current code is in testing phase. Do NOT use for research purposes...\n\n";
}

void DisplayMainMenu(){
	std::cout << "##################################################################################\n";
	std::cout << "#                                    Main Menu                                   #\n";
	std::cout << "#     1) Take single immediate reading                                           #\n";
	std::cout << "#     2) Take multiple evenly spaced readings for defined length of time (NO!)   #\n";
	std::cout << "#     3) Take multiple evenly spaced readings for undefined length of time       #\n";
	std::cout << "#     4) Exit                                                                    #\n";
	std::cout << "#                                                                                #\n";
	std::cout << "##################################################################################\n";
}

void UndefinedLengthTest(){
	system("cls");
	std::ofstream dataFile;
	std::string operatorName, projectName, specimenID, fileName;
	int lengthType, intervalType;
	double lengthTest, intervalTest;
	char dum;
	std::cout << "DEFINED LENGTH TEST SETUP\n";
	std::cout << "Data file will be stored in same directory as this executable.\nYou may add any extension to it.\nDate and time are automatically pulled from this computer and added to data file.\n";
	std::cout << "Filename: ";
	std::cin >> fileName;

	dataFile.open(fileName, std::ios::out);

	std::cout << "Operator Name: ";
	std::cin >> operatorName;
	dataFile << operatorName << std::endl;

	std::cout << "\nProject Name: ";
	std::cin >> projectName;
	dataFile << projectName << std::endl;

	std::cout << "\nSpecimen Name/ID: ";
	std::cin >> specimenID;
	dataFile << specimenID << std::endl;

	std::time_t curTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
	dataFile << curTime << std::endl;
	dataFile << "Time (min), Resistance (kOhms)" << std::endl;

	// Future work for defined length test function
	/*std::cout << "\nWould you like to enter the length of testing in\n1) minutes\n2) hours\n3) days\n4) weeks\nChoice: ";
	std::cin >> lengthType;
	std::cout << "\nHow long should the test run ";
	switch (lengthType){
	case 1:
		std::cout << "(minutes): ";
		std::cin >> lengthTest;
		break;
	case 2:
		std::cout << "(hours): ";
		std::cin >> lengthTest;
		break;
	case 3:
		std::cout << "(days): ";
		std::cin >> lengthTest;
		break;
	case 4:
		std::cout << "(weeks): ";
		std::cin >> lengthTest;
		break;
	default:
		std::cout << "(INVALID CHOICE, RETURN TO MAIN MENU): ";
		std::cin >> lengthTest;
		return;
		break;
	}*/
	std::cout << "\nWould you like to enter the interval of sampling in\n1) hertz\n2) minutes\nChoice: ";
	std::cin >> intervalType;
	switch (intervalType){
	case 1:
		std::cout << "\nEnter sampling interval (Hz): ";
		std::cin >> intervalTest;
		intervalTest = 1.0 / intervalTest;
		break;
	case 2:
		std::cout << "\nEnter sampling interval (minutes): ";
		std::cin >> intervalTest;
		intervalTest = intervalTest * 60.0;
		break;
	default:
		std::cout << "\nINVALID CHOICE, RETURN TO MAIN MENU";
		std::cin >> intervalTest;
		return;
		break;
	}

	// Get timer value ready. Value is in 100 nanosecond intervals
	timerValue.QuadPart = intervalTest*1E7;

	std::cout << "\nPress any key to start test...";
	std::cin >> dum;

	bool stopRecording = false;
	int count = 0;
	timer = CreateWaitableTimer(NULL, TRUE, NULL);
	double tempResistance, tempTime;

	while (stopRecording == false){
		SetWaitableTimer(timer, &timerValue, 0, NULL, NULL, 0);
		tempResistance = GetResistance();
		tempTime = (double)(count*intervalTest) / 60;
		dataFile << tempTime << ", ";
		dataFile << tempResistance << std::endl;
		system("cls");
		std::cout << "CURRENT TEST STATUS\n";
		std::cout << tempTime << " minutes into testing.\n";
		std::cout << count + 1 << " data points saved so far.\n";
		std::cout << tempResistance << " kOhms (most current data point).\n\n";
		std::cout << "Hit (ESC) key to stop data recording. Program will stop after next data point is collected...";

		// Duct tape way to get a decent timer function
		if (WaitForSingleObject(timer, INFINITE) != WAIT_OBJECT_0)
			dataFile << "Timer function failed due to error code " << GetLastError();
		else{
			if (GetAsyncKeyState(VK_ESCAPE)){
				stopRecording = true;
			}
		}

	}

}

int main() {
	char TestInterface;
	char dummy;
	int choice;
	DisplayHeader();
	std::cout << "Initializing serial port interface...";
	int PortOpen = InitializePort();
	if (PortOpen = 0) {
		std::cout << "no Resipod device found!\n";
		std::cout << "Press any key to terminate program...";
		std::cin >> dummy;
		return(EXIT_FAILURE);
	}
	else {
		std::cout << "success!\n\n";
		std::cout << "Resipod device is on COM" << PortOpen << "\n";
		std::cout << "Press any key to continue...";
		std::cin >> dummy;
	}

	do{
		system("cls");
		DisplayHeader();
		DisplayMainMenu();
		char dum;
		std::cout << "\n\n\nEnter choice: ";
		std::cin >> choice;
		switch (choice){
		case 1:
			double resistance;
			std::cout << "\n\nMeasuring resistance...";
			resistance = GetResistance();
			if (resistance > 0){
				std::cout << "success!\n\nResistance measured: " << resistance << " kOhms\n";
				std::cout << "Press any key to return to main menu...";
				std::cin >> dum;
			}
			else{
				std::cout << "failure!\n\nReturn byte incorrect. Try again or check serial parameters...\n";
				std::cout << "Press any key to return to main menu...";
				std::cin >> dum;
			}
			break;
		case 2:
			//DefinedLengthTest();

			std::cout << "\nNOT PROGRAMMED YET, RETURNING TO MAIN MENU! PRESS ANY KEY...";
			std::cin >> dum;
			break;
		case 3:
			UndefinedLengthTest();
			break;
		case 4:
			break;
		default:
			break;
		}
	} while (choice != 4);
}<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName			:		NFIWS.h
//    @Author			:		Stone.xin
//    @Date				:		2016-12-22
//    @Module			:		NFIWS
// -------------------------------------------------------------------------

#include "NFCWS.h"
#include <string.h>
#include <atomic>

bool NFCWS::Execute()
{
	m_EndPoint.poll();
	return false;
}

int NFCWS::Initialization(const unsigned int nMaxClient, const unsigned short nPort, const int nCpuCount)
{
	mnPort = nPort;
	mnMaxConnect = nMaxClient;
	mnCpuCount = nCpuCount;

	m_EndPoint.listen(nPort);
	m_EndPoint.start_accept();

	return 0;
}

bool NFCWS::Final()
{
	CloseSocketAll();
	m_EndPoint.stop();

	return true;
}

bool NFCWS::SendMsgToAllClient(const char * msg, const uint32_t nLen)
{
	if (nLen <= 0)
	{
		return false;
	}

	session_list::iterator it = mmObject.begin();
	while (it!=mmObject.end())
	{
		WSObjectPtr pWSObject = it->second;
		if (pWSObject && !pWSObject->NeedRemove())
		{
			try
			{
				m_EndPoint.send(it->first, msg, nLen, websocketpp::frame::opcode::TEXT);
			}
			catch (websocketpp::exception& e)
			{
				std::cout<<"websocket exception: "<<e.what()<<std::endl;
				return false;
			}
		}
		it++;
	}

	return true;
}

bool NFCWS::SendMsgToClient(const char * msg, const uint32_t nLen, std::vector<websocketpp::connection_hdl> vList)
{
	for (auto vIt:vList)
	{
		auto pWSObject = GetNetObject(vIt);
		if (pWSObject && !pWSObject->NeedRemove())
		{
			try
			{
				m_EndPoint.send(vIt, msg, nLen, websocketpp::frame::opcode::TEXT);
			}
			catch (websocketpp::exception& e)
			{
				std::cout << "websocket exception: " << e.what() << std::endl;
				return false;
			}
		}
	}
}

bool NFCWS::SendMsgToClient(const char * msg, const uint32_t nLen, websocketpp::connection_hdl hd)
{
	auto pWSObject = GetNetObject(hd);
	if (pWSObject && !pWSObject->NeedRemove())
	{
		try
		{
			m_EndPoint.send(hd, msg, nLen, websocketpp::frame::opcode::TEXT);
		}
		catch (websocketpp::exception& e)
		{
			std::cout << "websocket exception: " << e.what() << std::endl;
			return false;
		}
	}
	return true;
}

bool NFCWS::AddNetObject(websocketpp::connection_hdl hd,WSObjectPtr pWSObject)
{
	auto pObject = GetNetObject(hd);
	if (pObject)
	{
		return false;
	}
	mmObject.emplace(session_list::value_type(hd,pWSObject));
	return true;
}

WSObjectPtr NFCWS::GetNetObject(websocketpp::connection_hdl hd)
{
	session_list::iterator it = mmObject.find(hd);
	if (it == mmObject.end())
	{
		return nullptr;
	}
	return it->second;
}

void NFCWS::ExecuteClose()
{
	for each (auto vIt in mvRemoveObject)
	{
		CloseObject(vIt);
	}
	mvRemoveObject.clear();
}

bool NFCWS::CloseSocketAll()
{
	session_list::iterator it = mmObject.begin();
	for (it; it != mmObject.end(); ++it)
	{
		mvRemoveObject.push_back(it->first);
	}

	ExecuteClose();

	mmObject.clear();

	return true;
}

void NFCWS::CloseObject(websocketpp::connection_hdl hd, int nCloseCode/* =1000 */, const std::string& strCloseReason/* ="" */)
{
	m_EndPoint.close(hd, nCloseCode, strCloseReason);
}

void NFCWS::OnMessageHandler(websocketpp::connection_hdl hd, NFWebSockConf::message_ptr msg)
{
	auto pObject = GetNetObject(hd);
	if (!pObject)
	{
		return;
	}

	if (mRecvCB)
	{
		mRecvCB(hd,msg->get_payload());
	}
}

void NFCWS::OnOpenHandler(websocketpp::connection_hdl hd)
{
	WSObjectPtr pWSObject(NF_NEW(WSObject));
	if (AddNetObject(hd,pWSObject))
	{
		if (mEventCB)
		{
			mEventCB(hd, NF_WS_EVENT_OPEN);
		}
	}
}

bool NFCWS::RemoveConnection(websocketpp::connection_hdl hd, NF_WS_EVENT evt, int nCloseCode /* = 1000 */, const std::string& strCloseReason /* = "" */)
{
	session_list::iterator it = mmObject.find(hd);
	if (it != mmObject.end())
	{
		mvRemoveObject.push_back(hd);
		return true;
	}
	return false;
}

void NFCWS::OnCloseHandler(websocketpp::connection_hdl hd)
{
	RemoveConnection(hd, NF_WS_EVENT_CLOSE);
}

void NFCWS::OnFailHandler(websocketpp::connection_hdl hd)
{
	RemoveConnection(hd, NF_WS_EVENT_FAIL);
}

void NFCWS::OnInterruptHandler(websocketpp::connection_hdl hd)
{
	RemoveConnection(hd, NF_WS_EVENT_INTERRUPT);
}

bool NFCWS::OnPongHandler(websocketpp::connection_hdl hd, std::string str)
{
	return true;
}

void NFCWS::OnPongTimeOutHandler(websocketpp::connection_hdl hd, std::string str)
{
	RemoveConnection(hd, NF_WS_EVENT_PONG_TIMEOUT);
}
<commit_msg>use poll_one instead of poll<commit_after>// -------------------------------------------------------------------------
//    @FileName			:		NFIWS.h
//    @Author			:		Stone.xin
//    @Date				:		2016-12-22
//    @Module			:		NFIWS
// -------------------------------------------------------------------------

#include "NFCWS.h"
#include <string.h>
#include <atomic>

bool NFCWS::Execute()
{
	m_EndPoint.poll_one();
	return false;
}

int NFCWS::Initialization(const unsigned int nMaxClient, const unsigned short nPort, const int nCpuCount)
{
	mnPort = nPort;
	mnMaxConnect = nMaxClient;
	mnCpuCount = nCpuCount;

	m_EndPoint.listen(nPort);
	m_EndPoint.start_accept();

	return 0;
}

bool NFCWS::Final()
{
	CloseSocketAll();
	m_EndPoint.stop_listening();

	return true;
}

bool NFCWS::SendMsgToAllClient(const char * msg, const uint32_t nLen)
{
	if (nLen <= 0)
	{
		return false;
	}

	session_list::iterator it = mmObject.begin();
	while (it!=mmObject.end())
	{
		WSObjectPtr pWSObject = it->second;
		if (pWSObject && !pWSObject->NeedRemove())
		{
			try
			{
				m_EndPoint.send(it->first, msg, nLen, websocketpp::frame::opcode::TEXT);
			}
			catch (websocketpp::exception& e)
			{
				std::cout<<"websocket exception: "<<e.what()<<std::endl;
				return false;
			}
		}
		it++;
	}

	return true;
}

bool NFCWS::SendMsgToClient(const char * msg, const uint32_t nLen, std::vector<websocketpp::connection_hdl> vList)
{
	for (auto vIt:vList)
	{
		auto pWSObject = GetNetObject(vIt);
		if (pWSObject && !pWSObject->NeedRemove())
		{
			try
			{
				m_EndPoint.send(vIt, msg, nLen, websocketpp::frame::opcode::TEXT);
			}
			catch (websocketpp::exception& e)
			{
				std::cout << "websocket exception: " << e.what() << std::endl;
				return false;
			}
		}
	}
}

bool NFCWS::SendMsgToClient(const char * msg, const uint32_t nLen, websocketpp::connection_hdl hd)
{
	auto pWSObject = GetNetObject(hd);
	if (pWSObject && !pWSObject->NeedRemove())
	{
		try
		{
			m_EndPoint.send(hd, msg, nLen, websocketpp::frame::opcode::TEXT);
		}
		catch (websocketpp::exception& e)
		{
			std::cout << "websocket exception: " << e.what() << std::endl;
			return false;
		}
	}
	return true;
}

bool NFCWS::AddNetObject(websocketpp::connection_hdl hd,WSObjectPtr pWSObject)
{
	auto pObject = GetNetObject(hd);
	if (pObject)
	{
		return false;
	}
	mmObject.emplace(session_list::value_type(hd,pWSObject));
	return true;
}

WSObjectPtr NFCWS::GetNetObject(websocketpp::connection_hdl hd)
{
	session_list::iterator it = mmObject.find(hd);
	if (it == mmObject.end())
	{
		return nullptr;
	}
	return it->second;
}

void NFCWS::ExecuteClose()
{
	for each (auto vIt in mvRemoveObject)
	{
		CloseObject(vIt);
	}
	mvRemoveObject.clear();
}

bool NFCWS::CloseSocketAll()
{
	session_list::iterator it = mmObject.begin();
	for (it; it != mmObject.end(); ++it)
	{
		mvRemoveObject.push_back(it->first);
	}

	ExecuteClose();

	mmObject.clear();

	return true;
}

void NFCWS::CloseObject(websocketpp::connection_hdl hd, int nCloseCode/* =1000 */, const std::string& strCloseReason/* ="" */)
{
	m_EndPoint.close(hd, nCloseCode, strCloseReason);
}

void NFCWS::OnMessageHandler(websocketpp::connection_hdl hd, NFWebSockConf::message_ptr msg)
{
	auto pObject = GetNetObject(hd);
	if (!pObject)
	{
		return;
	}

	if (mRecvCB)
	{
		mRecvCB(hd,msg->get_payload());
	}
}

void NFCWS::OnOpenHandler(websocketpp::connection_hdl hd)
{
	WSObjectPtr pWSObject(NF_NEW(WSObject));
	if (AddNetObject(hd,pWSObject))
	{
		if (mEventCB)
		{
			mEventCB(hd, NF_WS_EVENT_OPEN);
		}
	}
}

bool NFCWS::RemoveConnection(websocketpp::connection_hdl hd, NF_WS_EVENT evt, int nCloseCode /* = 1000 */, const std::string& strCloseReason /* = "" */)
{
	session_list::iterator it = mmObject.find(hd);
	if (it != mmObject.end())
	{
		mvRemoveObject.push_back(hd);
		return true;
	}
	return false;
}

void NFCWS::OnCloseHandler(websocketpp::connection_hdl hd)
{
	RemoveConnection(hd, NF_WS_EVENT_CLOSE);
}

void NFCWS::OnFailHandler(websocketpp::connection_hdl hd)
{
	RemoveConnection(hd, NF_WS_EVENT_FAIL);
}

void NFCWS::OnInterruptHandler(websocketpp::connection_hdl hd)
{
	RemoveConnection(hd, NF_WS_EVENT_INTERRUPT);
}

bool NFCWS::OnPongHandler(websocketpp::connection_hdl hd, std::string str)
{
	return true;
}

void NFCWS::OnPongTimeOutHandler(websocketpp::connection_hdl hd, std::string str)
{
	RemoveConnection(hd, NF_WS_EVENT_PONG_TIMEOUT);
}
<|endoftext|>


<commit_before>//
// Name:	 Contours.cpp
// Purpose:  Contour-related code, which interfaces vtlib to the
//	QuikGrid library.
//
// Copyright (c) 2004-2008 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "vtlib/vtlib.h"

#if SUPPORT_QUIKGRID
#include "vtdata/QuikGrid.h"
#include "Contours.h"
#include <vtlib/core/TiledGeom.h>

//
// This callback function will receive points output from QuikGrid.
//
void ReceiveContourPoint(void *context, float x, float y, bool bStart)
{
	vtContourConverter *cc = (vtContourConverter *) context;
	cc->Coord(x, y, bStart);
}

/////////////////////////////////////////////////////////////////////////////
// class vtContourConverter

vtContourConverter::vtContourConverter()
{
	m_pMF = NULL;
	m_pGrid = NULL;
}

vtContourConverter::~vtContourConverter()
{
	delete m_pMF;
	delete m_pGrid;
}

/**
 * Set up the class to do draping on a terrain.
 *
 * \param pTerr The terrain you will generate the contour lines on.
 * \param color The colors of the generated lines.
 * \param fHeight The height above the terrain to drape the lines.  Generally
 *		you will want to use a small offset value here, to keep the lines from
 *		colliding with the terrain itself.
 * \return A geometry node which contains the contours.
 */
vtGeom *vtContourConverter::Setup(vtTerrain *pTerr, const RGBf &color, float fHeight)
{
	if (!pTerr)
		return NULL;

	// Make a note of this terrain and its attributes
	m_pTerrain = pTerr;
	m_pHF = pTerr->GetHeightFieldGrid3d();
	int tileLod0Size = 0;
	if (!m_pHF)
	{
		vtTiledGeom *tiledGeom = pTerr->GetTiledGeom();
		m_ext = tiledGeom->GetEarthExtents();
		//get highest LOD
		int minLod = 0;
		for(int i = 0; i < tiledGeom->rows * tiledGeom->rows; i++)
			if (tiledGeom->m_elev_info.lodmap.m_min[i] > minLod)
				minLod = tiledGeom->m_elev_info.lodmap.m_min[i];

		tileLod0Size = pow(2.0, minLod);
		m_spacing = DPoint2(m_ext.Width() / (tiledGeom->cols * tileLod0Size), m_ext.Height() / (tiledGeom->rows *tileLod0Size));
	}
	else
	{
		m_ext = m_pHF->GetEarthExtents();
		m_spacing = m_pHF->GetSpacing();
	}
	m_fHeight = fHeight;

	// Create material and geometry to contain the vector geometry
	vtMaterialArray *pMats = new vtMaterialArray;
	pMats->AddRGBMaterial1(color, false, false, true);

	m_pGeom = new vtGeom;
	m_pGeom->SetName2("Contour Geometry");
	m_pGeom->SetMaterials(pMats);
	pMats->Release();		// pass ownership

	// copy data from our grid to a QuikGrid object
	int nx, ny;
	if (m_pHF)
		m_pHF->GetDimensions(nx, ny);
	else
	{
		vtTiledGeom *tiledGeom = pTerr->GetTiledGeom();
		nx = tiledGeom->cols * tileLod0Size + 1;
		ny = tiledGeom->rows * tileLod0Size + 1;
	}
	m_pGrid = new SurfaceGrid(nx,ny);
	int i, j;
	if (m_pHF)
	{
		for (i = 0; i < nx; i++)
		{
			for (j = 0; j < ny; j++)
			{
				// use the true elevation, for true contours
				m_pGrid->zset(i, j, m_pHF->GetElevation(i, j, true));
			}
		}
	}
	else
	{
		vtTiledGeom *tiledGeom = pTerr->GetTiledGeom();
		float topBottom = tiledGeom->m_WorldExtents.top - tiledGeom->m_WorldExtents.bottom;
		float rightLeft = tiledGeom->m_WorldExtents.right - tiledGeom->m_WorldExtents.left;
		float rlxwidth = rightLeft / (tiledGeom->cols * tileLod0Size + 1);
		float tbywidth = topBottom / (tiledGeom->rows * tileLod0Size + 1);
		float altitude;
		for (i = 0; i < nx; i++)
		{
			for (j = 0; j < ny; j++)
			{
				// use the true elevation, for true contours
				tiledGeom->FindAltitudeAtPoint(FPoint3(i*rlxwidth, 0, j*tbywidth),altitude, true);
				m_pGrid->zset(i, j, altitude);
			}
		}
	}
	m_pMF = new vtMeshFactory(m_pGeom, vtMesh::LINE_STRIP, 0, 30000, 0);

	return m_pGeom;
}

/**
 * Generate a contour line to be draped on the terrain.
 *
 * \param fAlt The altitude (elevation) of the line to be generated.
 */
void vtContourConverter::GenerateContour(float fAlt)
{
	SetQuikGridCallbackFunction(ReceiveContourPoint, this);
	Contour(*m_pGrid, fAlt);
}

/**
 * Generate a set of contour lines to be draped on the terrain.
 *
 * \param fInterval  The vertical spacing between the contours.  For example,
 *		if the elevation range of your data is from 50 to 350 meters, then
 *		an fIterval of 100 will place contour bands at 100,200,300 meters.
 */
void vtContourConverter::GenerateContours(float fInterval)
{
	float fMin, fMax;
	if (m_pHF)
		m_pHF->GetHeightExtents(fMin, fMax);
	else
		m_pTerrain->GetTiledGeom()->GetHeightExtents(fMin, fMax);

	int start = (int) (fMin / fInterval) + 1;
	int stop = (int) (fMax / fInterval);

	SetQuikGridCallbackFunction(ReceiveContourPoint, this);
	for (int i = start; i <= stop; i++)
		Contour(*m_pGrid, i * fInterval);
}

void vtContourConverter::Coord(float x, float y, bool bStart)
{
	if (bStart)
		Flush();

	DPoint2 p2;
	p2.x = m_ext.left + x * m_spacing.x;
	p2.y = m_ext.bottom + y * m_spacing.y;
	m_line.Append(p2);
}

/**
 * Finishes the contour generation process.  Call once when you are done
 * using the class to generate contours.
 */
void vtContourConverter::Finish()
{
	Flush();

	// Add the geometry to the terrain's scaled features, so that it will scale
	//  up/down with the terrain's vertical exaggeration.
	m_pTerrain->GetScaledFeatures()->AddChild(m_pGeom);
}

void vtContourConverter::Flush()
{
	if (m_line.GetSize() > 2)
	{
		bool bInterpolate = false;		// no need; it already hugs the ground
		bool bCurve = false;			// no need; it's already quite smooth
		bool bUseTrueElevation = true;	// use true elevation, not scaled

		m_pTerrain->AddSurfaceLineToMesh(m_pMF, m_line, m_fHeight,
			bInterpolate, bCurve, bUseTrueElevation);
	}
	m_line.Empty();
}

#endif // SUPPORT_QUIKGRID

<commit_msg>avoid small compiler warning in contour module<commit_after>//
// Name:	 Contours.cpp
// Purpose:  Contour-related code, which interfaces vtlib to the
//	QuikGrid library.
//
// Copyright (c) 2004-2008 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "vtlib/vtlib.h"

#if SUPPORT_QUIKGRID
#include "vtdata/QuikGrid.h"
#include "Contours.h"
#include <vtlib/core/TiledGeom.h>

//
// This callback function will receive points output from QuikGrid.
//
void ReceiveContourPoint(void *context, float x, float y, bool bStart)
{
	vtContourConverter *cc = (vtContourConverter *) context;
	cc->Coord(x, y, bStart);
}

/////////////////////////////////////////////////////////////////////////////
// class vtContourConverter

vtContourConverter::vtContourConverter()
{
	m_pMF = NULL;
	m_pGrid = NULL;
}

vtContourConverter::~vtContourConverter()
{
	delete m_pMF;
	delete m_pGrid;
}

/**
 * Set up the class to do draping on a terrain.
 *
 * \param pTerr The terrain you will generate the contour lines on.
 * \param color The colors of the generated lines.
 * \param fHeight The height above the terrain to drape the lines.  Generally
 *		you will want to use a small offset value here, to keep the lines from
 *		colliding with the terrain itself.
 * \return A geometry node which contains the contours.
 */
vtGeom *vtContourConverter::Setup(vtTerrain *pTerr, const RGBf &color, float fHeight)
{
	if (!pTerr)
		return NULL;

	// Make a note of this terrain and its attributes
	m_pTerrain = pTerr;
	m_pHF = pTerr->GetHeightFieldGrid3d();
	int tileLod0Size = 0;
	if (!m_pHF)
	{
		vtTiledGeom *tiledGeom = pTerr->GetTiledGeom();
		m_ext = tiledGeom->GetEarthExtents();
		//get highest LOD
		int minLod = 0;
		for(int i = 0; i < tiledGeom->rows * tiledGeom->rows; i++)
			if (tiledGeom->m_elev_info.lodmap.m_min[i] > minLod)
				minLod = tiledGeom->m_elev_info.lodmap.m_min[i];

		tileLod0Size = 1 << minLod;
		m_spacing = DPoint2(m_ext.Width() / (tiledGeom->cols * tileLod0Size), m_ext.Height() / (tiledGeom->rows *tileLod0Size));
	}
	else
	{
		m_ext = m_pHF->GetEarthExtents();
		m_spacing = m_pHF->GetSpacing();
	}
	m_fHeight = fHeight;

	// Create material and geometry to contain the vector geometry
	vtMaterialArray *pMats = new vtMaterialArray;
	pMats->AddRGBMaterial1(color, false, false, true);

	m_pGeom = new vtGeom;
	m_pGeom->SetName2("Contour Geometry");
	m_pGeom->SetMaterials(pMats);
	pMats->Release();		// pass ownership

	// copy data from our grid to a QuikGrid object
	int nx, ny;
	if (m_pHF)
		m_pHF->GetDimensions(nx, ny);
	else
	{
		vtTiledGeom *tiledGeom = pTerr->GetTiledGeom();
		nx = tiledGeom->cols * tileLod0Size + 1;
		ny = tiledGeom->rows * tileLod0Size + 1;
	}
	m_pGrid = new SurfaceGrid(nx,ny);
	int i, j;
	if (m_pHF)
	{
		for (i = 0; i < nx; i++)
		{
			for (j = 0; j < ny; j++)
			{
				// use the true elevation, for true contours
				m_pGrid->zset(i, j, m_pHF->GetElevation(i, j, true));
			}
		}
	}
	else
	{
		vtTiledGeom *tiledGeom = pTerr->GetTiledGeom();
		float topBottom = tiledGeom->m_WorldExtents.top - tiledGeom->m_WorldExtents.bottom;
		float rightLeft = tiledGeom->m_WorldExtents.right - tiledGeom->m_WorldExtents.left;
		float rlxwidth = rightLeft / (tiledGeom->cols * tileLod0Size + 1);
		float tbywidth = topBottom / (tiledGeom->rows * tileLod0Size + 1);
		float altitude;
		for (i = 0; i < nx; i++)
		{
			for (j = 0; j < ny; j++)
			{
				// use the true elevation, for true contours
				tiledGeom->FindAltitudeAtPoint(FPoint3(i*rlxwidth, 0, j*tbywidth),altitude, true);
				m_pGrid->zset(i, j, altitude);
			}
		}
	}
	m_pMF = new vtMeshFactory(m_pGeom, vtMesh::LINE_STRIP, 0, 30000, 0);

	return m_pGeom;
}

/**
 * Generate a contour line to be draped on the terrain.
 *
 * \param fAlt The altitude (elevation) of the line to be generated.
 */
void vtContourConverter::GenerateContour(float fAlt)
{
	SetQuikGridCallbackFunction(ReceiveContourPoint, this);
	Contour(*m_pGrid, fAlt);
}

/**
 * Generate a set of contour lines to be draped on the terrain.
 *
 * \param fInterval  The vertical spacing between the contours.  For example,
 *		if the elevation range of your data is from 50 to 350 meters, then
 *		an fIterval of 100 will place contour bands at 100,200,300 meters.
 */
void vtContourConverter::GenerateContours(float fInterval)
{
	float fMin, fMax;
	if (m_pHF)
		m_pHF->GetHeightExtents(fMin, fMax);
	else
		m_pTerrain->GetTiledGeom()->GetHeightExtents(fMin, fMax);

	int start = (int) (fMin / fInterval) + 1;
	int stop = (int) (fMax / fInterval);

	SetQuikGridCallbackFunction(ReceiveContourPoint, this);
	for (int i = start; i <= stop; i++)
		Contour(*m_pGrid, i * fInterval);
}

void vtContourConverter::Coord(float x, float y, bool bStart)
{
	if (bStart)
		Flush();

	DPoint2 p2;
	p2.x = m_ext.left + x * m_spacing.x;
	p2.y = m_ext.bottom + y * m_spacing.y;
	m_line.Append(p2);
}

/**
 * Finishes the contour generation process.  Call once when you are done
 * using the class to generate contours.
 */
void vtContourConverter::Finish()
{
	Flush();

	// Add the geometry to the terrain's scaled features, so that it will scale
	//  up/down with the terrain's vertical exaggeration.
	m_pTerrain->GetScaledFeatures()->AddChild(m_pGeom);
}

void vtContourConverter::Flush()
{
	if (m_line.GetSize() > 2)
	{
		bool bInterpolate = false;		// no need; it already hugs the ground
		bool bCurve = false;			// no need; it's already quite smooth
		bool bUseTrueElevation = true;	// use true elevation, not scaled

		m_pTerrain->AddSurfaceLineToMesh(m_pMF, m_line, m_fHeight,
			bInterpolate, bCurve, bUseTrueElevation);
	}
	m_line.Empty();
}

#endif // SUPPORT_QUIKGRID

<|endoftext|>


<commit_before><commit_msg>fix typo<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <time.h>
#include <assert.h>
#include "IntervalTree.h"

using namespace std;

typedef Interval<bool> interval;
typedef vector<interval> intervalVector;
typedef IntervalTree<bool> intervalTree;

template<typename K>
K randKey(K floor, K ceiling) {
    K range = ceiling - floor;
    return floor + range * ((double) rand() / (double) (RAND_MAX + 1.0));
}

template<class T, typename K>
Interval<T,K> randomInterval(K maxStart, K maxLength, K maxStop, const T& value) {
    K start = randKey<K>(0, maxStart);
    K stop = min<K>(randKey<K>(start, start + maxLength), maxStop);
    return Interval<T,K>(start, stop, value);
}

int main() {
    typedef vector<std::size_t> countsVector;

    // a simple sanity check
    intervalVector sanityIntervals;
    sanityIntervals.push_back(interval(60, 80, true));
    sanityIntervals.push_back(interval(20, 40, true));
    intervalTree sanityTree(sanityIntervals);

    intervalVector sanityResults;
    sanityTree.findOverlapping(30, 50, sanityResults);
    assert(sanityResults.size() == 1);
    sanityResults.clear();
    sanityTree.findContained(15, 45, sanityResults);
    assert(sanityResults.size() == 1);

    srand((unsigned)time(NULL));

    intervalVector intervals;
    intervalVector queries;

    // generate a test set of target intervals
    for (int i = 0; i < 10000; ++i) {
        intervals.push_back(randomInterval<bool, unsigned long>(100000, 1000, 100000 + 1, true));
    }
    // and queries
    for (int i = 0; i < 5000; ++i) {
        queries.push_back(randomInterval<bool, unsigned long>(100000, 1000, 100000 + 1, true));
    }

    typedef chrono::high_resolution_clock Clock;
    typedef chrono::milliseconds milliseconds;

    // using brute-force search
    countsVector bruteforcecounts;
    Clock::time_point t0 = Clock::now();
    for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) {
        intervalVector results;
        for (intervalVector::iterator i = intervals.begin(); i != intervals.end(); ++i) {
            if (i->start >= q->start && i->stop <= q->stop) {
                results.push_back(*i);
            }
        }
        bruteforcecounts.push_back(results.size());
    }
    Clock::time_point t1 = Clock::now();
    milliseconds ms = chrono::duration_cast<milliseconds>(t1 - t0);
    cout << "brute force:\t" << ms.count() << "ms" << endl;

    // using the interval tree
    intervalTree tree = intervalTree(intervals);
    countsVector treecounts;
    t0 = Clock::now();
    for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) {
        intervalVector results;
        tree.findContained(q->start, q->stop, results);
        treecounts.push_back(results.size());
    }
    t1 = Clock::now();
    ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
    cout << "interval tree:\t" << ms.count() << "ms" << endl;

    // check that the same number of results are returned
    countsVector::iterator b = bruteforcecounts.begin();
    for (countsVector::iterator t = treecounts.begin(); t != treecounts.end(); ++t, ++b) {
        assert(*b == *t);
    }

    return 0;
}

<commit_msg>Add code to run the test framework<commit_after>#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <time.h>
#include <assert.h>
#include "IntervalTree.h"
#define CATCH_CONFIG_RUNNER // Mark this as file as the test-runner for catch
#include "catch.hpp"        // Include the catch unit test framework

using namespace std;

typedef Interval<bool> interval;
typedef vector<interval> intervalVector;
typedef IntervalTree<bool> intervalTree;

template<typename K>
K randKey(K floor, K ceiling) {
    K range = ceiling - floor;
    return floor + range * ((double) rand() / (double) (RAND_MAX + 1.0));
}

template<class T, typename K>
Interval<T,K> randomInterval(K maxStart, K maxLength, K maxStop, const T& value) {
    K start = randKey<K>(0, maxStart);
    K stop = min<K>(randKey<K>(start, start + maxLength), maxStop);
    return Interval<T,K>(start, stop, value);
}

int main(int argc, char**argv) {
    typedef vector<std::size_t> countsVector;

    // a simple sanity check
    intervalVector sanityIntervals;
    sanityIntervals.push_back(interval(60, 80, true));
    sanityIntervals.push_back(interval(20, 40, true));
    intervalTree sanityTree(sanityIntervals);

    intervalVector sanityResults;
    sanityTree.findOverlapping(30, 50, sanityResults);
    assert(sanityResults.size() == 1);
    sanityResults.clear();
    sanityTree.findContained(15, 45, sanityResults);
    assert(sanityResults.size() == 1);

    srand((unsigned)time(NULL));

    intervalVector intervals;
    intervalVector queries;

    // generate a test set of target intervals
    for (int i = 0; i < 10000; ++i) {
        intervals.push_back(randomInterval<bool, unsigned long>(100000, 1000, 100000 + 1, true));
    }
    // and queries
    for (int i = 0; i < 5000; ++i) {
        queries.push_back(randomInterval<bool, unsigned long>(100000, 1000, 100000 + 1, true));
    }

    typedef chrono::high_resolution_clock Clock;
    typedef chrono::milliseconds milliseconds;

    // using brute-force search
    countsVector bruteforcecounts;
    Clock::time_point t0 = Clock::now();
    for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) {
        intervalVector results;
        for (intervalVector::iterator i = intervals.begin(); i != intervals.end(); ++i) {
            if (i->start >= q->start && i->stop <= q->stop) {
                results.push_back(*i);
            }
        }
        bruteforcecounts.push_back(results.size());
    }
    Clock::time_point t1 = Clock::now();
    milliseconds ms = chrono::duration_cast<milliseconds>(t1 - t0);
    cout << "brute force:\t" << ms.count() << "ms" << endl;

    // using the interval tree
    intervalTree tree = intervalTree(intervals);
    countsVector treecounts;
    t0 = Clock::now();
    for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) {
        intervalVector results;
        tree.findContained(q->start, q->stop, results);
        treecounts.push_back(results.size());
    }
    t1 = Clock::now();
    ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
    cout << "interval tree:\t" << ms.count() << "ms" << endl;

    // check that the same number of results are returned
    countsVector::iterator b = bruteforcecounts.begin();
    for (countsVector::iterator t = treecounts.begin(); t != treecounts.end(); ++t, ++b) {
        assert(*b == *t);
    }

    return Catch::Session().run( argc, argv );
}

<|endoftext|>


<commit_before>#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <time.h>
#include <assert.h>
#include "IntervalTree.h"

using namespace std;

typedef Interval<bool,int> interval;
typedef vector<interval> intervalVector;
typedef IntervalTree<bool,int> intervalTree;

template<typename K>
K randKey(K floor, K ceiling) {
    K range = ceiling - floor;
    return floor + range * ((double) rand() / (double) (RAND_MAX + 1.0));
}

template<class T, typename K>
Interval<T,K> randomInterval(K maxStart, K maxLength, K maxStop, const T& value) {
    K start = randKey<K>(0, maxStart);
    K stop = min<K>(randKey<K>(start, start + maxLength), maxStop);
    return Interval<T,K>(start, stop, value);
}

int main() {
    typedef vector<std::size_t> countsVector;

    srand((unsigned)time(NULL));

    intervalVector intervals;
    intervalVector queries;

    // generate a test set of target intervals
    for (int i = 0; i < 10000; ++i) {
        intervals.push_back(randomInterval<bool,int>(100000, 1000, 100000 + 1, true));
    }
    // and queries
    for (int i = 0; i < 5000; ++i) {
        queries.push_back(randomInterval<bool,int>(100000, 1000, 100000 + 1, true));
    }

    typedef chrono::high_resolution_clock Clock;
    typedef chrono::milliseconds milliseconds;

    // using brute-force search
    countsVector bruteforcecounts;
    Clock::time_point t0 = Clock::now();
    for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) {
        intervalVector results;
        for (intervalVector::iterator i = intervals.begin(); i != intervals.end(); ++i) {
            if (i->start >= q->start && i->stop <= q->stop) {
                results.push_back(*i);
            }
        }
        bruteforcecounts.push_back(results.size());
    }
    Clock::time_point t1 = Clock::now();
    milliseconds ms = chrono::duration_cast<milliseconds>(t1 - t0);
    cout << "brute force:\t" << ms.count() << "ms" << endl;

    // using the interval tree
    //IntervalTree<bool> tree(intervals);
    intervalTree tree;
    tree = intervalTree(intervals);
    countsVector treecounts;
    t0 = Clock::now();
    for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) {
        intervalVector results;
        tree.findContained(q->start, q->stop, results);
        treecounts.push_back(results.size());
    }
    t1 = Clock::now();
    ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
    cout << "interval tree:\t" << ms.count() << "ms" << endl;

    // check that the same number of results are returned
    countsVector::iterator b = bruteforcecounts.begin();
    for (countsVector::iterator t = treecounts.begin(); t != treecounts.end(); ++t, ++b) {
        assert(*b == *t);
    }

    return 0;
}

<commit_msg>Cleanup.<commit_after>#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <time.h>
#include <assert.h>
#include "IntervalTree.h"

using namespace std;

typedef Interval<bool,int> interval;
typedef vector<interval> intervalVector;
typedef IntervalTree<bool,int> intervalTree;

template<typename K>
K randKey(K floor, K ceiling) {
    K range = ceiling - floor;
    return floor + range * ((double) rand() / (double) (RAND_MAX + 1.0));
}

template<class T, typename K>
Interval<T,K> randomInterval(K maxStart, K maxLength, K maxStop, const T& value) {
    K start = randKey<K>(0, maxStart);
    K stop = min<K>(randKey<K>(start, start + maxLength), maxStop);
    return Interval<T,K>(start, stop, value);
}

int main() {
    typedef vector<std::size_t> countsVector;

    srand((unsigned)time(NULL));

    intervalVector intervals;
    intervalVector queries;

    // generate a test set of target intervals
    for (int i = 0; i < 10000; ++i) {
        intervals.push_back(randomInterval<bool,int>(100000, 1000, 100000 + 1, true));
    }
    // and queries
    for (int i = 0; i < 5000; ++i) {
        queries.push_back(randomInterval<bool,int>(100000, 1000, 100000 + 1, true));
    }

    typedef chrono::high_resolution_clock Clock;
    typedef chrono::milliseconds milliseconds;

    // using brute-force search
    countsVector bruteforcecounts;
    Clock::time_point t0 = Clock::now();
    for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) {
        intervalVector results;
        for (intervalVector::iterator i = intervals.begin(); i != intervals.end(); ++i) {
            if (i->start >= q->start && i->stop <= q->stop) {
                results.push_back(*i);
            }
        }
        bruteforcecounts.push_back(results.size());
    }
    Clock::time_point t1 = Clock::now();
    milliseconds ms = chrono::duration_cast<milliseconds>(t1 - t0);
    cout << "brute force:\t" << ms.count() << "ms" << endl;

    // using the interval tree
    intervalTree tree = intervalTree(intervals);
    countsVector treecounts;
    t0 = Clock::now();
    for (intervalVector::iterator q = queries.begin(); q != queries.end(); ++q) {
        intervalVector results;
        tree.findContained(q->start, q->stop, results);
        treecounts.push_back(results.size());
    }
    t1 = Clock::now();
    ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
    cout << "interval tree:\t" << ms.count() << "ms" << endl;

    // check that the same number of results are returned
    countsVector::iterator b = bruteforcecounts.begin();
    for (countsVector::iterator t = treecounts.begin(); t != treecounts.end(); ++t, ++b) {
        assert(*b == *t);
    }

    return 0;
}

<|endoftext|>